﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using cszmcaux;
using System.Reflection.Emit;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Data;
using HalconDotNet;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
using System.Drawing;
using OpenCvSharp;
using SSVisionCom;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace CMT
{
    public class AxisParameter
    {
        //轴1
        public float Axis1Speed = 0;
        public float Axis1Units = 1;
        public float Axis1Accel = 1;
        public float Axis1Decel = 1;
        public float Axis1Mpos = 0;
        public float Axis1FsLimit = 0;
        public float Axis1RsLimit = 0;
        

        //轴2
        public float Axis2Speed = 0;
        public float Axis2Units = 1;
        public float Axis2Accel = 1;
        public float Axis2Decel = 1;
        public float Axis2Mpos = 0;
        public float Axis2FsLimit = 0;
        public float Axis2RsLimit = 0;

        //轴3
        public float Axis3Speed = 0;
        public float Axis3Units = 1;
        public float Axis3Accel = 1;
        public float Axis3Decel = 1;
        public float Axis3Mpos = 0;
        public float Axis3FsLimit = 0;
        public float Axis3RsLimit = 0;

        //轴4
        public float Axis4Speed = 0;
        public float Axis4Units = 1;
        public float Axis4Accel = 1;
        public float Axis4Decel = 1;
        public float Axis4Mpos = 0;
        public float Axis4FsLimit = 0;
        public float Axis4RsLimit = 0;

        //轴5
        public float Axis5Speed = 0;
        public float Axis5Units = 1;
        public float Axis5Accel = 1;
        public float Axis5Decel = 1;
        public float Axis5Mpos = 0;
        public float Axis5FsLimit = 0;
        public float Axis5RsLimit = 0;

        //轴6
        public float Axis6Speed = 0;
        public float Axis6Units = 1;
        public float Axis6Accel = 1;
        public float Axis6Decel = 1;
        public float Axis6Mpos = 0;
        public float Axis6FsLimit = 0;
        public float Axis6RsLimit = 0;

        //轴参数
        public const float Resolution = 262144;
        public float Station_Left_SafetyHight = 0;
        public float Station_Right_SafetyHight = 0;
        public float Station_Left_Zoffset = 0;
        public float Station_Right_Zoffset = 0;




    }

    public struct ScreenResult
    {
        public bool ScreenClass;
        public bool ScreenDisp;
        public bool IsEmpty;

    }
    public class Config
    {

        public string Camera1Seria = "";
        public string Camera2Seria = "";
        public string Camera3Seria = "";
        public string Camera4Seria = "";
        public string Camera5Seria = "";
        public string Camera6Seria = "";
        public string Camera7Seria = "";
        public string Camera8Seria = "";

        public string UserId = "";
        public string UserPassword = "";
        public bool Regionfoshan = false;
        public float LeftHomeX = 0;
        public float LeftHomeY = -40;
        public float LeftHomeZ = 0;
        public float RightHomeX = 0;
        public float RightHomeY = -40;
        public float RightHomeZ = 0;
        public float Amendment_X_Left = 0;
        public float Amendment_Y_Left = 0;
        public float Amendment_Z_Left = 0;
        public float Amendment_X_Right = 0;
        public float Amendment_Y_Right = 0;
        public float Amendment_Z_Right = 0;
        public int MotionControl = 4;
        public int algorithmicMode = 0;
        public string TestBoard_Left_PortName = "";
        public string TestBoard_Right_PortName = "";
        public double SavaImageTime = 0;
        public string CurrentMode = "Defualt";
        public bool PLC_Start = false;
        public string PLCIP = "192.168.10.180";
        public PLC_Commumication_address PLC_address = new PLC_Commumication_address();
        public bool Shield_ScreenTest = false;
        public bool Shield_KeyTest = false;
        public Dictionary<string, int> Total_Item = new Dictionary<string, int>();
        public string ToDay = "";
        public Product product_Now = new Product();
        public List<Product> productList = new List<Product>();
        public Dictionary<string, MotionControl_Info> MotionControl_List = new Dictionary<string, MotionControl_Info>();
        public List<string> Screen_Model_List = new List<string>();
        public List<string> Key_Model_List = new List<string>();
    }

    public class MotionControl_Info
    {
        public Motioncontrol motioncontrol_Left = new Motioncontrol();
        public Motioncontrol motioncontrol_Right = new Motioncontrol();
    }

    public class PLC_Commumication_address
    {
        public string StartLeft = "";
        public string GetMateriel_Left = "";
        public string TestComplete_Left = "";
        public string TestReult1_Left = "";
        public string TestReult2_Left = "";
        public string TestReult3_Left = "";
        public string TestReult4_Left = "";

        public string StartRight = "";
        public string GetMateriel_Right = "";
        public string TestComplete_Right = "";
        public string TestReult1_Right = "";
        public string TestReult2_Right = "";
        public string TestReult3_Right = "";
        public string TestReult4_Right = "";

        public string Left_StationIsEmpty = "";
        public string Right_StationIsEmpty = "";
    }
    public class Motioncontrol
    {
        public  IntPtr Phandle;
        public List<MotionPoint> motionPoints = new List<MotionPoint>();
    }
    public class Product:ICloneable
    {
        public Motioncontrol motioncontrol_Left = new Motioncontrol();
        public Motioncontrol motioncontrol_Right = new Motioncontrol();
        public List<IR_Feature> IR_List = new List<IR_Feature>();
        public int IR_Count = 0;
        public string Model = "Defult";
        public Formula Config = new Formula();
        public Product_Style P_Style;
        public double GetScreen_Scaled_Value1 = 0;
        public double GetScreen_Scaled_Value2 = 0;
        public int Screen_AreaMin = 175;
        public int Key_AreaMin = 200;

        public string MotionControl_Name = "";
        public string Screen_Model = "";
        public string Key_Model = "";
        public enum Product_Style
        {
            RomoteControl_White = 0,
            RomoteControl_black = 1
        }
        public object Clone()
        {
            object tempData = new object();
            string temp = JsonConvert.SerializeObject(this);
            tempData = JsonConvert.DeserializeObject<Product>(temp);
            return tempData;
        }
    }

    public class IR_Feature
    {
        public string IR_KeyName = "";
        public string IR_Code = ""; 
    }

    public class MotionPoint
    {
        public IntPtr Phandle;
        public int[] AxisList;
        public PointStyle pointStyle;
        public string Name;
        public float X;
        public float Y;
        public float Up_Z=0;
        public float Down_Z;
        public int DelayTime_Up;
        public int DelayTime_Down;
        public int IO_address;
        public uint IO_state;
        public string Code_Value;
        public List<string> IR_Code_List = new List<string>();
        float[] PList = new float[] { 0,0,0 };
        public float Zoffset = 0;
        public float SafetyHight = 0;
        public uint StartLeftWait;
        public uint StartRightWait;
        public bool execute(String direction)
        {

            bool excuteResult = false;
            switch (pointStyle)
            {
                case PointStyle.IOContrlo:
                    zmcaux.ZAux_Direct_SetOp(Phandle, IO_address, IO_state);
                    Thread.Sleep(DelayTime_Up);
                    break;
                case PointStyle.KeyTest:
                    PList[0] = X;
                    PList[1] = Y;
                    PList[2] = Up_Z;
                    zmcaux.ZAux_Direct_MoveAbs(Phandle,3,AxisList,PList);
                    AxisEndOf();
                    PList[2] = Down_Z+Zoffset;
                    AxisEndOf();
                    zmcaux.ZAux_Direct_MoveAbs(Phandle, 3, AxisList, PList);
                    AxisEndOf();
                    Thread.Sleep(DelayTime_Down);
                    PList[2] = Up_Z;
                    zmcaux.ZAux_Direct_MoveAbs(Phandle, 3, AxisList, PList);
                    AxisEndOf();
                    Thread.Sleep(DelayTime_Up);
                    break;
                case PointStyle.Camera:
                    PList[0] = X;
                    PList[1] = Y;
                    PList[2] = Up_Z;
                    zmcaux.ZAux_Direct_MoveAbs(Phandle, 3, AxisList, PList);
                    AxisEndOf();
                    Thread.Sleep(DelayTime_Up);
                    Console.WriteLine("拍照一次");
                    break;
                case PointStyle.KeyTest_IO:
                    PList[0] = X;
                    PList[1] = Y;
                    PList[2] = Up_Z;
                    zmcaux.ZAux_Direct_MoveAbs(Phandle, 3, AxisList, PList);
                    zmcaux.ZAux_Direct_SetOp(Phandle, IO_address, IO_state);
                    AxisEndOf();
                    PList[2] = Down_Z;
                    AxisEndOf();
                    Thread.Sleep(DelayTime_Up);
                    zmcaux.ZAux_Direct_MoveAbs(Phandle, 3, AxisList, PList);
                    zmcaux.ZAux_Direct_SetOp(Phandle, IO_address, 0);
                    break;
                case PointStyle.Move:
                    PList[0] = X;
                    PList[1] = Y;
                    PList[2] = Up_Z;
                    zmcaux.ZAux_Direct_MoveAbs(Phandle, 3, AxisList, PList);
                    AxisEndOf();
                    Thread.Sleep(DelayTime_Up);
                    break;
                case PointStyle.Wait:
                    PList[0] = X;
                    PList[1] = Y;
                    PList[2] = Up_Z;
                    AxisEndOf();
                    Thread.Sleep(DelayTime_Up);
                    Console.WriteLine("等待");
                    while (direction != null)
                    {
                        zmcaux.ZAux_Direct_GetIn(Phandle, 64, ref StartLeftWait);
                        zmcaux.ZAux_Direct_GetIn(Phandle, 67, ref StartRightWait);
                        if (direction == "Right")
                        {
                            if (Convert.ToBoolean(StartRightWait) == true)
                            {
                                break;
                            }
                        }
                        if (direction == "Left")
                        {
                            if (Convert.ToBoolean(StartLeftWait) == true)
                            {
                                break;
                            }
                        }
                    }
                    break;

            }
            return excuteResult;
        }
        private void AxisEndOf()
        {
            int AxisXState = 0;
            int AxisYState = 0;
            int AxisZState = 0;
            while (true)
            {
                zmcaux.ZAux_Direct_GetIfIdle(Phandle, AxisList[0], ref AxisXState);
                zmcaux.ZAux_Direct_GetIfIdle(Phandle, AxisList[1], ref AxisYState);
                zmcaux.ZAux_Direct_GetIfIdle(Phandle, AxisList[2], ref AxisZState);

                if (AxisXState == -1 && AxisYState == -1 && AxisZState == -1)
                {
                    break;
                }
                Application.DoEvents();
            }
               
        }

    }
    public enum PointStyle
    {
        IOContrlo = 0,
        KeyTest = 1,
        Camera = 2,
        KeyTest_IO = 3,
        Move = 4,
        Wait = 5
    }



    public class PLC_Position
    {
        public float Position_X;
        public float Position_Y;
        public float Position_Z;
        public Int32 Point_Delay;
        public string Point_Style;
        public string Explain;
    }
    //产品配方
    public class Formula
    {
        public double CarrierFrequencyMax = 0;
        public double CarrierFrequencyMin = 0;
        public double DynamiccurrentMax = 0;
        public double QuiescentCurrentMax = 0;
        public double DynamiccurrentMin = 0;
        public double QuiescentCurrentMin = 0;
        public double RadiancyLeft_Channel1 = 0;
        public double RadiancyLeft_Channel2 = 0;
        public double RadiancyLeft_Channel3 = 0;
        public double RadiancyLeft_Channel4 = 0;

        public double RadiancyRight_Channel1 = 0;
        public double RadiancyRight_Channel2 = 0;
        public double RadiancyRight_Channel3 = 0;
        public double RadiancyRight_Channel4 = 0;



        public float Camera1ExposureTime = 5500;
        public float Camera2ExposureTime = 6500;
        public float Camera3ExposureTime = 5000;
        public float Camera4ExposureTime = 7500;
        public float Camera5ExposureTime = 6000;
        public float Camera6ExposureTime = 6000;
        public float Camera7ExposureTime = 5500;
        public float Camera8ExposureTime = 6000;

        public int ScreenGrayval = 100;
        public int KeyGrayva=100;
        public List<int> ScreenGrayvalList = new List<int>();
        public List<int> KeyGrayvallist = new List<int>();

    }
    //测试信息
    public class TestResult
    {
        public TestStation TestLeft = new TestStation("测试左");
        public TestStation TestRight = new TestStation("测试右");

    }
    //测试工位的定义
    public class TestStation
    {
        public string StationName = "";
        public TestChannel Channel1;
        public TestChannel Channel2;
        public TestChannel Channel3;
        public TestChannel Channel4;



        public TestStation(string stationName)
        {
            this.StationName = stationName;
            Channel1 = new TestChannel(StationName + "Channel1");
            Channel2 = new TestChannel(StationName + "Channel2");
            Channel3 = new TestChannel(StationName + "Channel3");
            Channel4 = new TestChannel(StationName + "Channel4");
        }

        public void Clean()
        {
            Channel1.Clean();
            Channel2.Clean();
            Channel3.Clean();
            Channel4.Clean();
        }

    }
    // 测试通道
    public class TestChannel
    {
        public string IR_Code_Now = "";
        public string ChanelName = "";
        public List<string> IR_TestItem = new List<string>();
        public List<double> Dynamiccurrent = new List<double>();
        public List<string> IR_Code = new List<string>();
        public List<double> Radiancy = new List<double>();
        public List<bool> ScreenTest = new List<bool>();
        public List<double> CarrierFrequency = new List<double>();
        public double Dynamiccurrent_Max { get; set; }//动态电流结果
        public double Radiancy_Min { get; set; }//辐照度最小值
        public bool IR_Result { set; get; }// 红外测试结果
        public double QuiescentCurrent { set; get; } // 静态电流结果
        public ScreenResult Test_item_LCD;//液晶屏幕识别的结果
        public bool Test_item_Key = false;//按键丝印结果
        public int IR_Feature_Count = 0;
        public bool KeyIsEmpty = false;
        public bool ScreenIsEmpty = false;
        public bool ProductIsEmpty = false;
        public TestChannel(string channelName)
        {
            this.ChanelName = channelName;
        }

        public void Clean()
        {
            IR_Result = false;
            QuiescentCurrent = 0;
            Dynamiccurrent_Max = 0;
            Radiancy_Min = 0;
            IR_TestItem.Clear();
            Dynamiccurrent.Clear();
            Radiancy.Clear();
            ScreenTest.Clear();
            CarrierFrequency.Clear();
            IR_Feature_Count = 0;
            ProductIsEmpty = false;
            IR_Code.Clear();
        }



        public bool GetTestResult(Product product,Config configFile, out string NgInfo,bool ScreenCheckState,bool KeyCheckState,string Localtion,int CodeCount)
        {

            bool Result = false;
            List<bool> IR_Compare = new List<bool>();

            int NoPower = 0;//通过这个计数判断是否上电


            // 获取红外结果
            if (IR_TestItem.Count > 0)
            {
                if(IR_TestItem.Count==1 && IR_TestItem[0].Contains("放电"))
                {
                    IR_Result = true;
                }
                else
                {
                    IR_Result = false;
                    NoPower++;//1
                }

            }
            else
            {
                IR_Result = true;
            }



            //辐照度最小值
            if (Radiancy.Count > 0)
            {
                Radiancy_Min = Radiancy.Max();
            }


            NgInfo = "";
            List<bool> JudegeResult = new List<bool>();
            JudegeResult.Clear();
            if ((QuiescentCurrent <= product.Config.QuiescentCurrentMax) && (QuiescentCurrent > product.Config.QuiescentCurrentMin))
            {
                JudegeResult.Add(true);
            }
            else
            {
                JudegeResult.Add(false);
                NgInfo = NgInfo + "静态电流异常\r\n";
                configFile.Total_Item["静态电流"]++;
            }

            if (CarrierFrequency.Count > 0)
            {
                for (int i = 0; i < CarrierFrequency.Count; i++)
                {
                    if (CarrierFrequency[i] < product.Config.CarrierFrequencyMin || CarrierFrequency[i] >product.Config.CarrierFrequencyMax)
                    {
                        NgInfo = NgInfo + "载波异常\r\n";
                        configFile.Total_Item["载波频率"]++;
                        break;
                    }
                }
            }
            else
            {
                NgInfo = NgInfo + "载波异常\r\n";
               
                JudegeResult.Add(false);


                NoPower++;//2
            }


            if (IR_Result=true && IR_TestItem.Count==0 && IR_Code.Count==product.IR_Count)
            {
                JudegeResult.Add(true);
            }
            else
            {
                JudegeResult.Add(false);
                NgInfo = NgInfo + "红外测试异常\r\n";
                NgInfo = NgInfo + "[";
                foreach (string str in IR_TestItem)
                {
                    NgInfo = NgInfo + str + "  ";
                }
                NgInfo = NgInfo + "];\n";

            }

            if (Dynamiccurrent.Count > 0)
            {

                if (Dynamiccurrent.Max() <= product.Config.DynamiccurrentMax && Dynamiccurrent.Min() >= product.Config.DynamiccurrentMin)
                {
                    JudegeResult.Add(true);
                }
                else
                {
                    NgInfo = NgInfo + "动态电流异常;";
                    NgInfo = NgInfo + "当前动态电流最小值:" + Dynamiccurrent.Min() + "\n";
                    JudegeResult.Add(false);

                    configFile.Total_Item["动态电流"]++;

                }
            }
            else
            {
                NgInfo = NgInfo + "动态电流异常;";
                NgInfo = NgInfo + "没有获取到动态电流\n";
                JudegeResult.Add(false);
                NoPower++;
            }



            double Value = 0;
            switch(Localtion)
            {
                case "Left1":
                    Value = product.Config.RadiancyLeft_Channel1;
                    break;
                case "Left2":
                    Value = product.Config.RadiancyLeft_Channel2;
                    break;
                case "Left3":
                    Value = product.Config.RadiancyLeft_Channel3;
                    break;
                case "Left4":
                    Value = product.Config.RadiancyLeft_Channel4;
                    break;

                case "Right1":
                    Value = product.Config.RadiancyRight_Channel1;
                    break;
                case "Right2":
                    Value = product.Config.RadiancyRight_Channel2;
                    break;
                case "Right3":
                    Value = product.Config.RadiancyRight_Channel3;
                    break;
                case "Right4":
                    Value = product.Config.RadiancyRight_Channel4;
                    break;
            }




            if (Radiancy.Count > 0  && Radiancy.Min()< Value)
            {
                NgInfo = NgInfo + "红外发光强度异常\n";
                JudegeResult.Add(false);
                configFile.Total_Item["发光强度"]++;
            }
            else
            {
                if(Radiancy.Count == 0)
                {
                    NgInfo = NgInfo + "红外发光强度异常\n";
                    JudegeResult.Add(false);
                    NoPower++;//3
                    configFile.Total_Item["发光强度"]++;
                }
                else
                {
                    JudegeResult.Add(true);
                }
               
            }

            if(Test_item_LCD.ScreenClass==true)
            {
                JudegeResult.Add(true);
            }
            else
            {
                if (configFile.Shield_ScreenTest == false)
                {
                    NgInfo = NgInfo + "屏幕类别异常\n";
                    configFile.Total_Item["屏幕"]++;
                    JudegeResult.Add(false);
                }
                else
                {
                    JudegeResult.Add(true);
                }
            }

            if(Test_item_LCD.ScreenDisp==true)
            {
                JudegeResult.Add(true);
            }
            else
            {
                if (configFile.Shield_ScreenTest == false)
                {
                    NgInfo = NgInfo + "屏幕显示异常\n";
                    JudegeResult.Add(false);
                    configFile.Total_Item["屏幕"]++;
                }
                else
                {
                    JudegeResult.Add(true);
                }
            }

            if(Test_item_Key == true)
            {
                JudegeResult.Add(true);
            }
            else
            {
                if(configFile.Shield_KeyTest==false)
                {
                    NgInfo = NgInfo + "按键检测异常\n";
                    JudegeResult.Add(false);
                    configFile.Total_Item["按键"]++;
                }
                else
                {
                    JudegeResult.Add(true);
                }
            }

           
            if(JudegeResult.Contains(false)==true)
            {
                Result = true;
            }
            else
            {
                Result = false;
                NgInfo = "产品测量OK\r\n";
            }



            if ((KeyIsEmpty == true && ScreenIsEmpty == true)|| NoPower == 3 )
            {
                ProductIsEmpty = true;
                configFile.Total_Item["空载"]++;
            }
            else
            {
                ProductIsEmpty = false;
            }



            return Result; 
        }


    }

    //图像处理算法过后的结果
    public class Result_ImageProcess
    {
        public bool Result_Seat1 { get; set; }
        public bool Result_Seat2 { get; set; }
    }
    //枚举数据库驱动
    /// <summary>
    /// 枚举Accesss数据库的驱动类型
    /// </summary>
    public enum AccessDriveMode
    {
        /// <summary>
        /// 32位驱动
        /// </summary>
        X86 = 1,
        /// <summary>
        /// 64位驱动
        /// </summary>
        X64 = 2
    }

    public class DataBaseQueryResult
    {
        /// <summary>
        /// 表示一个数据库操作是否成功的Boolean值
        /// </summary>
        public bool OperationResult;
        /// <summary>
        /// 为DataAdapter方法创建的一个存储数据的对象
        /// </summary>
        public DataSet ds = new DataSet();
        /// <summary>
        /// 为 DataReader方法创建的一个存储数据的对象
        /// </summary>
        public List<List<string>> Result = new List<List<string>>();
        /// <summary>
        /// 存放数据中的错误信息
        /// </summary>
        public string msg;
        /// <summary>
        /// 描述数据库操作当中受影响的行数
        /// </summary>
        public int ReturnRows;
    }
    public class AccessData
    {
        /// <summary>
        /// 描述一个Accesss数据库驱动的路径
        /// </summary>
        public string DataBaseSource { get; set; }
        /// <summary>
        /// 描述数据库的驱动类型
        /// </summary>
        public string DataBaseDrive { get; set; }
        /// <summary>
        /// AccessData 的构造函数
        /// </summary>
        /// <param name="DataBaseSource">数据库路径</param>
        /// <param name="driveMode">驱动类型</param>
        public AccessData(string DataBaseSource, AccessDriveMode driveMode)
        {
            this.DataBaseSource = DataBaseSource;
            if (driveMode == AccessDriveMode.X86)
            {
                this.DataBaseDrive = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=";
            }
            else
            {
                this.DataBaseDrive = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=";
            }
        }
        /// <summary>
        /// 执行数据的增，改，删等操作
        /// </summary>
        /// <param name="query">操作语句</param>
        /// <returns></returns>
        public int DataBaseOperation(string query)
        {
            int operation = 0;
            if (DataBaseSource == "")
            {
                MessageBox.Show("无法访问到正确的Access文件地址");
                operation = -1;
                goto lable1;
            }
            string conn = DataBaseDrive + DataBaseSource;
            try
            {
                OleDbConnection connection = new OleDbConnection(conn);
                connection.Open();
                OleDbCommand OleDbCommand = new OleDbCommand(query, connection);
                operation = OleDbCommand.ExecuteNonQuery();
                connection.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
                operation = -1;
            }
        lable1:
            return operation;
        }

        /// <summary>
        /// 想数据库中查询数据
        /// </summary>
        /// <param name="query">操作语句</param>
        /// <returns></returns>
        public DataBaseQueryResult DataBaseQuery(string query)
        {
            DataBaseQueryResult result = new DataBaseQueryResult();

            try
            {
                string conn = DataBaseDrive + DataBaseSource;
                OleDbConnection connection = new OleDbConnection(conn);
                connection.Open();
                OleDbCommand OleDbCommand = new OleDbCommand(query, connection);
                OleDbDataReader OleDbDataReader = OleDbCommand.ExecuteReader();
                while (OleDbDataReader.Read())
                {
                    List<string> column = new List<string>();
                    for (int i = 0; i < OleDbDataReader.FieldCount; i++)
                    {
                        column.Add(OleDbDataReader[i].ToString());
                    }
                    result.Result.Add(column);
                }
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connection);
                dataAdapter.Fill(result.ds);
                connection.Close();
                result.OperationResult = true;
            }
            catch (Exception error)
            {
                result.OperationResult = false;
                result.msg = error.Message;
            }

            return result;

        }


    }

    public class Algorithm
    {
        public double Scaled_Value1 = 3;
        public double Scaled_Value2 = -75;
        public int Screen_AreaMin = 150;
        public void GetImagePart(HObject ho_ImageRotate, HObject ho_ROI_0, out HObject ho_ImagePart1, HTuple hv_ang, out HTuple hv_HomMat2D)
        {




            // Local iconic variables 

            HObject ho_ImageReduced, ho_ImagePart, ho_ImageAffineTrans;
            HObject ho_ImageMean, ho_RegionDynThresh, ho_ConnectedRegions;
            HObject ho_RegionFillUp, ho_SelectedRegions, ho_RegionDilation;
            HObject ho_Rectangle, ho_ImageReduced1;

            // Local control variables 

            HTuple hv_Area = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart1);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_ImageAffineTrans);
            HOperatorSet.GenEmptyObj(out ho_ImageMean);
            HOperatorSet.GenEmptyObj(out ho_RegionDynThresh);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_RegionDilation);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced1);
            hv_HomMat2D = new HTuple();
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageRotate, ho_ROI_0, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            hv_HomMat2D.Dispose();
            HOperatorSet.VectorAngleToRigid(0, 0, hv_ang, 0, 0, 0, out hv_HomMat2D);
            ho_ImageAffineTrans.Dispose();
            HOperatorSet.AffineTransImage(ho_ImagePart, out ho_ImageAffineTrans, hv_HomMat2D,
                "constant", "false");
            ho_ImageMean.Dispose();
            HOperatorSet.MeanImage(ho_ImageAffineTrans, out ho_ImageMean, 99, 99);
            ho_RegionDynThresh.Dispose();
            HOperatorSet.DynThreshold(ho_ImageAffineTrans, ho_ImageMean, out ho_RegionDynThresh,
                3, "dark");
            ho_ConnectedRegions.Dispose();
            HOperatorSet.Connection(ho_RegionDynThresh, out ho_ConnectedRegions);
            ho_RegionFillUp.Dispose();
            HOperatorSet.FillUp(ho_ConnectedRegions, out ho_RegionFillUp);
            ho_SelectedRegions.Dispose();
            HOperatorSet.SelectShape(ho_RegionFillUp, out ho_SelectedRegions, (new HTuple("area")).TupleConcat(
                "rectangularity"), "and", (new HTuple(295000)).TupleConcat(0.7), (new HTuple(9999999)).TupleConcat(
                1));
            ho_RegionDilation.Dispose();
            HOperatorSet.DilationRectangle1(ho_SelectedRegions, out ho_RegionDilation, 50,
                50);
            hv_Area.Dispose(); hv_Row.Dispose(); hv_Column.Dispose();
            HOperatorSet.AreaCenter(ho_RegionDilation, out hv_Area, out hv_Row, out hv_Column);
            ho_Rectangle.Dispose();
            HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row, hv_Column, 0, 370, 500);
            ho_ImageReduced1.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageAffineTrans, ho_Rectangle, out ho_ImageReduced1
                );
            ho_ImagePart1.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced1, out ho_ImagePart1);
            ho_ImageReduced.Dispose();
            ho_ImagePart.Dispose();
            ho_ImageAffineTrans.Dispose();
            ho_ImageMean.Dispose();
            ho_RegionDynThresh.Dispose();
            ho_ConnectedRegions.Dispose();
            ho_RegionFillUp.Dispose();
            ho_SelectedRegions.Dispose();
            ho_RegionDilation.Dispose();
            ho_Rectangle.Dispose();
            ho_ImageReduced1.Dispose();

            hv_Area.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();

            return;
        }
        public void CreateModel(HObject ho_Image, HObject ho_ROI_0, HTuple hv_RegionPath, HTuple hv_ModelID_Paht, HTuple hv_ROI_Path)
        {
            // Local iconic variables 

            HObject ho_ImageGray, ho_ImageEquHisto, ho_ImageEmphasize1;
            HObject ho_ImageMedian, ho_Region, ho_RegionFillUp, ho_ConnectedRegions;
            HObject ho_SelectedRegions, ho_RegionErosion, ho_ImageReduced;
            HObject ho_MSERDark, ho_MSERLight, ho_RegionUnion;

            // Local control variables 

            HTuple hv_ModelID = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImageGray);
            HOperatorSet.GenEmptyObj(out ho_ImageEquHisto);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize1);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_RegionErosion);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_MSERDark);
            HOperatorSet.GenEmptyObj(out ho_MSERLight);
            HOperatorSet.GenEmptyObj(out ho_RegionUnion);

            ho_ImageGray.Dispose();
            HOperatorSet.Rgb3ToGray(ho_Image, ho_Image, ho_Image, out ho_ImageGray);
            ho_ImageEquHisto.Dispose();
            HOperatorSet.EquHistoImage(ho_ImageGray, out ho_ImageEquHisto);
            ho_ImageEmphasize1.Dispose();
            HOperatorSet.Emphasize(ho_ImageEquHisto, out ho_ImageEmphasize1, 15, 15, 1);
            ho_ImageMedian.Dispose();
            HOperatorSet.MedianImage(ho_ImageEmphasize1, out ho_ImageMedian, "circle", 3,
                "mirrored");
            ho_Region.Dispose();
            HOperatorSet.Threshold(ho_ImageMedian, out ho_Region, 0, 169);
            ho_RegionFillUp.Dispose();
            HOperatorSet.FillUp(ho_Region, out ho_RegionFillUp);
            ho_ConnectedRegions.Dispose();
            HOperatorSet.Connection(ho_RegionFillUp, out ho_ConnectedRegions);
            ho_SelectedRegions.Dispose();
            HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area",
                "and", 150, 99999999);
            ho_RegionErosion.Dispose();
            HOperatorSet.ErosionRectangle1(ho_SelectedRegions, out ho_RegionErosion, 11,
                21);
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageMedian, ho_ROI_0, out ho_ImageReduced);
            hv_ModelID.Dispose();
            HOperatorSet.CreateScaledShapeModel(ho_ImageReduced, "auto", 0, 6.28, "auto",
                0.9, 1.1, "auto", "auto", "use_polarity", "auto", "auto", out hv_ModelID);
            ho_MSERDark.Dispose(); ho_MSERLight.Dispose();
            HOperatorSet.SegmentImageMser(ho_ImageReduced, out ho_MSERDark, out ho_MSERLight,
                "dark", 10, 39999, 7, "max_gray", 90);
            ho_RegionUnion.Dispose();
            HOperatorSet.Union1(ho_MSERDark, out ho_RegionUnion);
            HOperatorSet.WriteRegion(ho_RegionUnion, hv_RegionPath);
            HOperatorSet.WriteShapeModel(hv_ModelID, hv_ModelID_Paht);
            HOperatorSet.WriteRegion(ho_ROI_0, hv_ROI_Path);

            ho_ImageGray.Dispose();
            ho_ImageEquHisto.Dispose();
            ho_ImageEmphasize1.Dispose();
            ho_ImageMedian.Dispose();
            ho_Region.Dispose();
            ho_RegionFillUp.Dispose();
            ho_ConnectedRegions.Dispose();
            ho_SelectedRegions.Dispose();
            ho_RegionErosion.Dispose();
            ho_ImageReduced.Dispose();
            ho_MSERDark.Dispose();
            ho_MSERLight.Dispose();
            ho_RegionUnion.Dispose();

            hv_ModelID.Dispose();

            return;
        }
        public void vision_yejingmianban(HObject ho_input_img, HObject ho_input_model_roi, HObject ho_input_model_region, out HObject ho_out_region1, HTuple hv_model_id, out HTuple hv_erro_ng)
        {
            // Local iconic variables 

            HObject ho_ImageGray, ho_ImageEquHisto, ho_ImageEmphasize1;
            HObject ho_ImageMedian, ho_Region, ho_RegionFillUp, ho_ConnectedRegions;
            HObject ho_SelectedRegions, ho_RegionErosion, ho_ImageReduced;
            HObject ho_MSERDark, ho_MSERLight, ho_RegionAffineTrans = null;
            HObject ho_RegionDifference = null, ho_RegionOpening = null;

            // Local control variables 

            HTuple hv_Area = new HTuple(), hv_Row1 = new HTuple();
            HTuple hv_Column1 = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Angle = new HTuple();
            HTuple hv_Scale = new HTuple(), hv_Score = new HTuple();
            HTuple hv_HomMat2DIdentity = new HTuple(), hv_HomMat2DRotate = new HTuple();
            HTuple hv_HomMat2DTranslate = new HTuple(), hv_HomMat2DScale = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_out_region1);
            HOperatorSet.GenEmptyObj(out ho_ImageGray);
            HOperatorSet.GenEmptyObj(out ho_ImageEquHisto);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize1);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_RegionErosion);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_MSERDark);
            HOperatorSet.GenEmptyObj(out ho_MSERLight);
            HOperatorSet.GenEmptyObj(out ho_RegionAffineTrans);
            HOperatorSet.GenEmptyObj(out ho_RegionDifference);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening);
            hv_erro_ng = new HTuple();
            try
            {
                ho_ImageGray.Dispose();
                HOperatorSet.Rgb3ToGray(ho_input_img, ho_input_img, ho_input_img, out ho_ImageGray
                    );
                ho_ImageEquHisto.Dispose();
                HOperatorSet.EquHistoImage(ho_ImageGray, out ho_ImageEquHisto);
                ho_ImageEmphasize1.Dispose();
                HOperatorSet.Emphasize(ho_ImageEquHisto, out ho_ImageEmphasize1, 15, 15, 1);
                ho_ImageMedian.Dispose();
                HOperatorSet.MedianImage(ho_ImageEmphasize1, out ho_ImageMedian, "circle",
                    3, "mirrored");
                ho_Region.Dispose();
                HOperatorSet.Threshold(ho_ImageMedian, out ho_Region, 0, 169);
                ho_RegionFillUp.Dispose();
                HOperatorSet.FillUp(ho_Region, out ho_RegionFillUp);
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_RegionFillUp, out ho_ConnectedRegions);
                ho_SelectedRegions.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area",
                    "and", 150, 99999999);
                ho_RegionErosion.Dispose();
                HOperatorSet.ErosionRectangle1(ho_SelectedRegions, out ho_RegionErosion, 11,
                    21);
                ho_ImageReduced.Dispose();
                HOperatorSet.ReduceDomain(ho_ImageMedian, ho_RegionErosion, out ho_ImageReduced
                    );
                ho_MSERDark.Dispose(); ho_MSERLight.Dispose();
                HOperatorSet.SegmentImageMser(ho_ImageReduced, out ho_MSERDark, out ho_MSERLight,
                    "dark", 10, 39999, 7, "max_gray", 90);
                hv_Area.Dispose(); hv_Row1.Dispose(); hv_Column1.Dispose();
                HOperatorSet.AreaCenter(ho_input_model_roi, out hv_Area, out hv_Row1, out hv_Column1);
                hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
                HOperatorSet.FindScaledShapeModel(ho_ImageMedian, hv_model_id, (new HTuple(-30)).TupleRad()
                        , (new HTuple(30)).TupleRad(), 0.9,
                    1.1, 0.2, 1, 0.5, (new HTuple("least_squares")).TupleConcat("max_deformation 3"),
                    0, 0.9, out hv_Row, out hv_Column, out hv_Angle, out hv_Scale, out hv_Score);
                if ((int)(new HTuple(hv_Row.TupleGreater(0))) != 0)
                {
                    hv_HomMat2DIdentity.Dispose();
                    HOperatorSet.HomMat2dIdentity(out hv_HomMat2DIdentity);
                    hv_HomMat2DRotate.Dispose();
                    HOperatorSet.HomMat2dRotate(hv_HomMat2DIdentity, hv_Angle, hv_Row, hv_Column,
                        out hv_HomMat2DRotate);
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        hv_HomMat2DTranslate.Dispose();
                        HOperatorSet.HomMat2dTranslate(hv_HomMat2DRotate, hv_Row - hv_Row1, hv_Column - hv_Column1,
                            out hv_HomMat2DTranslate);
                    }
                    hv_HomMat2DScale.Dispose();
                    HOperatorSet.HomMat2dScale(hv_HomMat2DTranslate, hv_Scale, hv_Scale, hv_Row,
                        hv_Column, out hv_HomMat2DScale);
                    ho_RegionAffineTrans.Dispose();
                    HOperatorSet.AffineTransRegion(ho_input_model_region, out ho_RegionAffineTrans,
                        hv_HomMat2DScale, "nearest_neighbor");
                    ho_RegionDifference.Dispose();
                    HOperatorSet.Difference(ho_RegionAffineTrans, ho_MSERDark, out ho_RegionDifference
                        );
                    ho_RegionOpening.Dispose();
                    HOperatorSet.OpeningRectangle1(ho_RegionDifference, out ho_RegionOpening,
                        3, 3);
                    ho_out_region1.Dispose();
                    HOperatorSet.Connection(ho_RegionOpening, out ho_out_region1);
                    hv_erro_ng.Dispose();
                    hv_erro_ng = 1;
                }
                else
                {
                    hv_erro_ng.Dispose();
                    hv_erro_ng = 0;
                }
                ho_ImageGray.Dispose();
                ho_ImageEquHisto.Dispose();
                ho_ImageEmphasize1.Dispose();
                ho_ImageMedian.Dispose();
                ho_Region.Dispose();
                ho_RegionFillUp.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_SelectedRegions.Dispose();
                ho_RegionErosion.Dispose();
                ho_ImageReduced.Dispose();
                ho_MSERDark.Dispose();
                ho_MSERLight.Dispose();
                ho_RegionAffineTrans.Dispose();
                ho_RegionDifference.Dispose();
                ho_RegionOpening.Dispose();

                hv_Area.Dispose();
                hv_Row1.Dispose();
                hv_Column1.Dispose();
                hv_Row.Dispose();
                hv_Column.Dispose();
                hv_Angle.Dispose();
                hv_Scale.Dispose();
                hv_Score.Dispose();
                hv_HomMat2DIdentity.Dispose();
                hv_HomMat2DRotate.Dispose();
                hv_HomMat2DTranslate.Dispose();
                hv_HomMat2DScale.Dispose();

                return;
            }
            catch (HalconException HDevExpDefaultException)
            {
                ho_ImageGray.Dispose();
                ho_ImageEquHisto.Dispose();
                ho_ImageEmphasize1.Dispose();
                ho_ImageMedian.Dispose();
                ho_Region.Dispose();
                ho_RegionFillUp.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_SelectedRegions.Dispose();
                ho_RegionErosion.Dispose();
                ho_ImageReduced.Dispose();
                ho_MSERDark.Dispose();
                ho_MSERLight.Dispose();
                ho_RegionAffineTrans.Dispose();
                ho_RegionDifference.Dispose();
                ho_RegionOpening.Dispose();

                hv_Area.Dispose();
                hv_Row1.Dispose();
                hv_Column1.Dispose();
                hv_Row.Dispose();
                hv_Column.Dispose();
                hv_Angle.Dispose();
                hv_Scale.Dispose();
                hv_Score.Dispose();
                hv_HomMat2DIdentity.Dispose();
                hv_HomMat2DRotate.Dispose();
                hv_HomMat2DTranslate.Dispose();
                hv_HomMat2DScale.Dispose();

                throw HDevExpDefaultException;
            }
        }
        public void disp_message(HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem, HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box)
        {



            // Local iconic variables 

            // Local control variables 

            HTuple hv_GenParamName = new HTuple(), hv_GenParamValue = new HTuple();
            HTuple hv_Color_COPY_INP_TMP = new HTuple(hv_Color);
            HTuple hv_Column_COPY_INP_TMP = new HTuple(hv_Column);
            HTuple hv_CoordSystem_COPY_INP_TMP = new HTuple(hv_CoordSystem);
            HTuple hv_Row_COPY_INP_TMP = new HTuple(hv_Row);

            // Initialize local and output iconic variables 
            //This procedure displays text in a graphics window.
            //
            //Input parameters:
            //WindowHandle: The WindowHandle of the graphics window, where
            //   the message should be displayed
            //String: A tuple of strings containing the text message to be displayed
            //CoordSystem: If set to 'window', the text position is given
            //   with respect to the window coordinate system.
            //   If set to 'image', image coordinates are used.
            //   (This may be useful in zoomed images.)
            //Row: The row coordinate of the desired text position
            //   A tuple of values is allowed to display text at different
            //   positions.
            //Column: The column coordinate of the desired text position
            //   A tuple of values is allowed to display text at different
            //   positions.
            //Color: defines the color of the text as string.
            //   If set to [], '' or 'auto' the currently set color is used.
            //   If a tuple of strings is passed, the colors are used cyclically...
            //   - if |Row| == |Column| == 1: for each new textline
            //   = else for each text position.
            //Box: If Box[0] is set to 'true', the text is written within an orange box.
            //     If set to' false', no box is displayed.
            //     If set to a color string (e.g. 'white', '#FF00CC', etc.),
            //       the text is written in a box of that color.
            //     An optional second value for Box (Box[1]) controls if a shadow is displayed:
            //       'true' -> display a shadow in a default color
            //       'false' -> display no shadow
            //       otherwise -> use given string as color string for the shadow color
            //
            //It is possible to display multiple text strings in a single call.
            //In this case, some restrictions apply:
            //- Multiple text positions can be defined by specifying a tuple
            //  with multiple Row and/or Column coordinates, i.e.:
            //  - |Row| == n, |Column| == n
            //  - |Row| == n, |Column| == 1
            //  - |Row| == 1, |Column| == n
            //- If |Row| == |Column| == 1,
            //  each element of String is display in a new textline.
            //- If multiple positions or specified, the number of Strings
            //  must match the number of positions, i.e.:
            //  - Either |String| == n (each string is displayed at the
            //                          corresponding position),
            //  - or     |String| == 1 (The string is displayed n times).
            //
            //
            //Convert the parameters for disp_text.
            if ((int)((new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr(
                new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(new HTuple())))) != 0)
            {

                hv_Color_COPY_INP_TMP.Dispose();
                hv_Column_COPY_INP_TMP.Dispose();
                hv_CoordSystem_COPY_INP_TMP.Dispose();
                hv_Row_COPY_INP_TMP.Dispose();
                hv_GenParamName.Dispose();
                hv_GenParamValue.Dispose();

                return;
            }
            if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0)
            {
                hv_Row_COPY_INP_TMP.Dispose();
                hv_Row_COPY_INP_TMP = 12;
            }
            if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0)
            {
                hv_Column_COPY_INP_TMP.Dispose();
                hv_Column_COPY_INP_TMP = 12;
            }
            //
            //Convert the parameter Box to generic parameters.
            hv_GenParamName.Dispose();
            hv_GenParamName = new HTuple();
            hv_GenParamValue.Dispose();
            hv_GenParamValue = new HTuple();
            if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(0))) != 0)
            {
                if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleEqual("false"))) != 0)
                {
                    //Display no box
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat(
                                "box");
                            hv_GenParamName.Dispose();
                            hv_GenParamName = ExpTmpLocalVar_GenParamName;
                        }
                    }
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat(
                                "false");
                            hv_GenParamValue.Dispose();
                            hv_GenParamValue = ExpTmpLocalVar_GenParamValue;
                        }
                    }
                }
                else if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleNotEqual("true"))) != 0)
                {
                    //Set a color other than the default.
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat(
                                "box_color");
                            hv_GenParamName.Dispose();
                            hv_GenParamName = ExpTmpLocalVar_GenParamName;
                        }
                    }
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat(
                                hv_Box.TupleSelect(0));
                            hv_GenParamValue.Dispose();
                            hv_GenParamValue = ExpTmpLocalVar_GenParamValue;
                        }
                    }
                }
            }
            if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(1))) != 0)
            {
                if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleEqual("false"))) != 0)
                {
                    //Display no shadow.
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat(
                                "shadow");
                            hv_GenParamName.Dispose();
                            hv_GenParamName = ExpTmpLocalVar_GenParamName;
                        }
                    }
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat(
                                "false");
                            hv_GenParamValue.Dispose();
                            hv_GenParamValue = ExpTmpLocalVar_GenParamValue;
                        }
                    }
                }
                else if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleNotEqual("true"))) != 0)
                {
                    //Set a shadow color other than the default.
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat(
                                "shadow_color");
                            hv_GenParamName.Dispose();
                            hv_GenParamName = ExpTmpLocalVar_GenParamName;
                        }
                    }
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat(
                                hv_Box.TupleSelect(1));
                            hv_GenParamValue.Dispose();
                            hv_GenParamValue = ExpTmpLocalVar_GenParamValue;
                        }
                    }
                }
            }
            //Restore default CoordSystem behavior.
            if ((int)(new HTuple(hv_CoordSystem_COPY_INP_TMP.TupleNotEqual("window"))) != 0)
            {
                hv_CoordSystem_COPY_INP_TMP.Dispose();
                hv_CoordSystem_COPY_INP_TMP = "image";
            }
            //
            if ((int)(new HTuple(hv_Color_COPY_INP_TMP.TupleEqual(""))) != 0)
            {
                //disp_text does not accept an empty string for Color.
                hv_Color_COPY_INP_TMP.Dispose();
                hv_Color_COPY_INP_TMP = new HTuple();
            }
            //
            HOperatorSet.DispText(hv_WindowHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
                hv_Row_COPY_INP_TMP, hv_Column_COPY_INP_TMP, hv_Color_COPY_INP_TMP, hv_GenParamName,
                hv_GenParamValue);

            hv_Color_COPY_INP_TMP.Dispose();
            hv_Column_COPY_INP_TMP.Dispose();
            hv_CoordSystem_COPY_INP_TMP.Dispose();
            hv_Row_COPY_INP_TMP.Dispose();
            hv_GenParamName.Dispose();
            hv_GenParamValue.Dispose();

            return;
        }
        public void set_display_font(HTuple hv_WindowHandle, HTuple hv_Size, HTuple hv_Font, HTuple hv_Bold, HTuple hv_Slant)
        {



            // Local iconic variables 

            // Local control variables 

            HTuple hv_OS = new HTuple(), hv_Fonts = new HTuple();
            HTuple hv_Style = new HTuple(), hv_Exception = new HTuple();
            HTuple hv_AvailableFonts = new HTuple(), hv_Fdx = new HTuple();
            HTuple hv_Indices = new HTuple();
            HTuple hv_Font_COPY_INP_TMP = new HTuple(hv_Font);
            HTuple hv_Size_COPY_INP_TMP = new HTuple(hv_Size);

            try
            {

                hv_OS.Dispose();
                HOperatorSet.GetSystem("operating_system", out hv_OS);
                if ((int)((new HTuple(hv_Size_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr(
                    new HTuple(hv_Size_COPY_INP_TMP.TupleEqual(-1)))) != 0)
                {
                    hv_Size_COPY_INP_TMP.Dispose();
                    hv_Size_COPY_INP_TMP = 16;
                }
                if ((int)(new HTuple(((hv_OS.TupleSubstr(0, 2))).TupleEqual("Win"))) != 0)
                {
                    //Restore previous behaviour
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_Size = ((1.13677 * hv_Size_COPY_INP_TMP)).TupleInt()
                                ;
                            hv_Size_COPY_INP_TMP.Dispose();
                            hv_Size_COPY_INP_TMP = ExpTmpLocalVar_Size;
                        }
                    }
                }
                else
                {
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_Size = hv_Size_COPY_INP_TMP.TupleInt()
                                ;
                            hv_Size_COPY_INP_TMP.Dispose();
                            hv_Size_COPY_INP_TMP = ExpTmpLocalVar_Size;
                        }
                    }
                }
                if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("Courier"))) != 0)
                {
                    hv_Fonts.Dispose();
                    hv_Fonts = new HTuple();
                    hv_Fonts[0] = "Courier";
                    hv_Fonts[1] = "Courier 10 Pitch";
                    hv_Fonts[2] = "Courier New";
                    hv_Fonts[3] = "CourierNew";
                    hv_Fonts[4] = "Liberation Mono";
                }
                else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("mono"))) != 0)
                {
                    hv_Fonts.Dispose();
                    hv_Fonts = new HTuple();
                    hv_Fonts[0] = "Consolas";
                    hv_Fonts[1] = "Menlo";
                    hv_Fonts[2] = "Courier";
                    hv_Fonts[3] = "Courier 10 Pitch";
                    hv_Fonts[4] = "FreeMono";
                    hv_Fonts[5] = "Liberation Mono";
                }
                else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("sans"))) != 0)
                {
                    hv_Fonts.Dispose();
                    hv_Fonts = new HTuple();
                    hv_Fonts[0] = "Luxi Sans";
                    hv_Fonts[1] = "DejaVu Sans";
                    hv_Fonts[2] = "FreeSans";
                    hv_Fonts[3] = "Arial";
                    hv_Fonts[4] = "Liberation Sans";
                }
                else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("serif"))) != 0)
                {
                    hv_Fonts.Dispose();
                    hv_Fonts = new HTuple();
                    hv_Fonts[0] = "Times New Roman";
                    hv_Fonts[1] = "Luxi Serif";
                    hv_Fonts[2] = "DejaVu Serif";
                    hv_Fonts[3] = "FreeSerif";
                    hv_Fonts[4] = "Utopia";
                    hv_Fonts[5] = "Liberation Serif";
                }
                else
                {
                    hv_Fonts.Dispose();
                    hv_Fonts = new HTuple(hv_Font_COPY_INP_TMP);
                }
                hv_Style.Dispose();
                hv_Style = "";
                if ((int)(new HTuple(hv_Bold.TupleEqual("true"))) != 0)
                {
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_Style = hv_Style + "Bold";
                            hv_Style.Dispose();
                            hv_Style = ExpTmpLocalVar_Style;
                        }
                    }
                }
                else if ((int)(new HTuple(hv_Bold.TupleNotEqual("false"))) != 0)
                {
                    hv_Exception.Dispose();
                    hv_Exception = "Wrong value of control parameter Bold";
                    throw new HalconException(hv_Exception);
                }
                if ((int)(new HTuple(hv_Slant.TupleEqual("true"))) != 0)
                {
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_Style = hv_Style + "Italic";
                            hv_Style.Dispose();
                            hv_Style = ExpTmpLocalVar_Style;
                        }
                    }
                }
                else if ((int)(new HTuple(hv_Slant.TupleNotEqual("false"))) != 0)
                {
                    hv_Exception.Dispose();
                    hv_Exception = "Wrong value of control parameter Slant";
                    throw new HalconException(hv_Exception);
                }
                if ((int)(new HTuple(hv_Style.TupleEqual(""))) != 0)
                {
                    hv_Style.Dispose();
                    hv_Style = "Normal";
                }
                hv_AvailableFonts.Dispose();
                HOperatorSet.QueryFont(hv_WindowHandle, out hv_AvailableFonts);
                hv_Font_COPY_INP_TMP.Dispose();
                hv_Font_COPY_INP_TMP = "";
                for (hv_Fdx = 0; (int)hv_Fdx <= (int)((new HTuple(hv_Fonts.TupleLength())) - 1); hv_Fdx = (int)hv_Fdx + 1)
                {
                    hv_Indices.Dispose();
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        hv_Indices = hv_AvailableFonts.TupleFind(
                            hv_Fonts.TupleSelect(hv_Fdx));
                    }
                    if ((int)(new HTuple((new HTuple(hv_Indices.TupleLength())).TupleGreater(
                        0))) != 0)
                    {
                        if ((int)(new HTuple(((hv_Indices.TupleSelect(0))).TupleGreaterEqual(0))) != 0)
                        {
                            hv_Font_COPY_INP_TMP.Dispose();
                            using (HDevDisposeHelper dh = new HDevDisposeHelper())
                            {
                                hv_Font_COPY_INP_TMP = hv_Fonts.TupleSelect(
                                    hv_Fdx);
                            }
                            break;
                        }
                    }
                }
                if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual(""))) != 0)
                {
                    throw new HalconException("Wrong value of control parameter Font");
                }
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    {
                        HTuple
                          ExpTmpLocalVar_Font = (((hv_Font_COPY_INP_TMP + "-") + hv_Style) + "-") + hv_Size_COPY_INP_TMP;
                        hv_Font_COPY_INP_TMP.Dispose();
                        hv_Font_COPY_INP_TMP = ExpTmpLocalVar_Font;
                    }
                }
                HOperatorSet.SetFont(hv_WindowHandle, hv_Font_COPY_INP_TMP);

                hv_Font_COPY_INP_TMP.Dispose();
                hv_Size_COPY_INP_TMP.Dispose();
                hv_OS.Dispose();
                hv_Fonts.Dispose();
                hv_Style.Dispose();
                hv_Exception.Dispose();
                hv_AvailableFonts.Dispose();
                hv_Fdx.Dispose();
                hv_Indices.Dispose();

                return;
            }
            catch (HalconException HDevExpDefaultException)
            {

                hv_Font_COPY_INP_TMP.Dispose();
                hv_Size_COPY_INP_TMP.Dispose();
                hv_OS.Dispose();
                hv_Fonts.Dispose();
                hv_Style.Dispose();
                hv_Exception.Dispose();
                hv_AvailableFonts.Dispose();
                hv_Fdx.Dispose();
                hv_Indices.Dispose();

                throw HDevExpDefaultException;
            }
        }
        public void Key_Create_ImagePart(HObject ho_ImageRotate, HObject ho_ROI_0, out HObject ho_ImagePart, HTuple hv_Model_Path, out HTuple hv_ModelID)
        {




            // Local iconic variables 

            HObject ho_ImageReduced, ho_Rectangle;

            // Local control variables 

            HTuple hv_Row = new HTuple(), hv_Column = new HTuple();
            HTuple hv_Angle = new HTuple(), hv_Scale = new HTuple();
            HTuple hv_Score = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            hv_ModelID = new HTuple();
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageRotate, ho_ROI_0, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                hv_ModelID.Dispose();
                HOperatorSet.CreateScaledShapeModel(ho_ImagePart, "auto", (new HTuple(-60)).TupleRad()
                    , (new HTuple(60)).TupleRad(), "auto", 0.9, 1.1, "auto", "auto", "use_polarity",
                    "auto", "auto", out hv_ModelID);
            }
            HOperatorSet.WriteShapeModel(hv_ModelID, hv_Model_Path);
            hv_ModelID.Dispose();
            HOperatorSet.ReadShapeModel(hv_Model_Path, out hv_ModelID);
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
            HOperatorSet.FindScaledShapeModel(ho_ImageRotate, hv_ModelID, -0.39, 0.78, 0.9,
                1.1, 0.5, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                out hv_Scale, out hv_Score);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row - 850, hv_Column, hv_Angle,
                    500, 1460);
            }
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageRotate, ho_Rectangle, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            ho_ImageReduced.Dispose();
            ho_Rectangle.Dispose();

            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Angle.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();

            return;
        }
        public void Key_Create_ImagePart_Black(HObject ho_ImageRotate, HObject ho_ROI_0, out HObject ho_ImagePart, HTuple hv_Model_Path, out HTuple hv_ModelID)
        {




            // Local iconic variables 

            HObject ho_ImageReduced, ho_Rectangle;

            // Local control variables 

            HTuple hv_Row = new HTuple(), hv_Column = new HTuple();
            HTuple hv_Angle = new HTuple(), hv_Scale = new HTuple();
            HTuple hv_Score = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            hv_ModelID = new HTuple();
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageRotate, ho_ROI_0, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                hv_ModelID.Dispose();
                HOperatorSet.CreateScaledShapeModel(ho_ImagePart, "auto", (new HTuple(-60)).TupleRad()
                    , (new HTuple(60)).TupleRad(), "auto", 0.9, 1.1, "auto", "auto", "use_polarity",
                    "auto", "auto", out hv_ModelID);
            }
            HOperatorSet.WriteShapeModel(hv_ModelID, hv_Model_Path);
            hv_ModelID.Dispose();
            HOperatorSet.ReadShapeModel(hv_Model_Path, out hv_ModelID);
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
            HOperatorSet.FindScaledShapeModel(ho_ImageRotate, hv_ModelID, -0.39, 0.78, 0.9,
                1.1, 0.5, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                out hv_Scale, out hv_Score);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row +100, hv_Column, hv_Angle,
                    510, 700);
            }
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageRotate, ho_Rectangle, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            ho_ImageReduced.Dispose();
            ho_Rectangle.Dispose();

            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Angle.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();

            return;
        }
        public void Key_GetImagePart(HObject ho_ImageRotate, out HObject ho_ImagePart, HTuple hv_Model_Path, out HTuple hv_Length)
        {
            // Local iconic variables 

            HObject ho_Rectangle = null, ho_ImageReduced = null;

            // Local control variables 

            HTuple hv_ModelID = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Angle = new HTuple();
            HTuple hv_Scale = new HTuple(), hv_Score = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            hv_Length = new HTuple();
            hv_ModelID.Dispose();
            HOperatorSet.ReadShapeModel(hv_Model_Path, out hv_ModelID);
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
            HOperatorSet.FindScaledShapeModel(ho_ImageRotate, hv_ModelID, -0.39, 0.78, 0.9,
                1.1, 0.5, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                out hv_Scale, out hv_Score);
            hv_Length.Dispose();
            HOperatorSet.TupleLength(hv_Score, out hv_Length);
            if ((int)(new HTuple(hv_Length.TupleGreater(0))) != 0)
            {
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    ho_Rectangle.Dispose();
                    HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row - 850, hv_Column, hv_Angle,
                        510, 1600);
                }
                ho_ImageReduced.Dispose();
                HOperatorSet.ReduceDomain(ho_ImageRotate, ho_Rectangle, out ho_ImageReduced
                    );
                ho_ImagePart.Dispose();
                HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            }
            ho_Rectangle.Dispose();
            ho_ImageReduced.Dispose();

            hv_ModelID.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Angle.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();

            return;
        }
        public void Key_GetImagePart_Black(HObject ho_ImageRotate, out HObject ho_ImagePart, HTuple hv_Model_Path)
        {




            // Local iconic variables 

            HObject ho_Rectangle, ho_ImageReduced;

            // Local control variables 

            HTuple hv_ModelID = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Angle = new HTuple();
            HTuple hv_Scale = new HTuple(), hv_Score = new HTuple();
            // Initialize local and output iconic variables 69
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            hv_ModelID.Dispose();
            HOperatorSet.ReadShapeModel(hv_Model_Path, out hv_ModelID);
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
            HOperatorSet.FindScaledShapeModel(ho_ImageRotate, hv_ModelID, -0.39, 0.78, 0.9,
                1.1, 0.5, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                out hv_Scale, out hv_Score);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row + 100, hv_Column, hv_Angle,
                    510, 700);
            }
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageRotate, ho_Rectangle, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            ho_Rectangle.Dispose();
            ho_ImageReduced.Dispose();

            hv_ModelID.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Angle.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();

            return;
        }
        public void CreateModel_Key(HObject ho_Image, HObject ho_ROI_0, out HObject ho_RegionUnion, HTuple hv_RegionPath, HTuple hv_ModelID_Paht, HTuple hv_ROI_Path)
        {




            // Local iconic variables 

            HObject ho_ImageEmphasize, ho_ImageMedian;
            HObject ho_ImageOpening, ho_GrayImage1, ho_ImageReduced;
            HObject ho_Region;

            // Local control variables 

            HTuple hv_ModelID = new HTuple(), hv_UsedThreshold = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_RegionUnion);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            HOperatorSet.GenEmptyObj(out ho_ImageOpening);
            HOperatorSet.GenEmptyObj(out ho_GrayImage1);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Region);
            ho_ImageEmphasize.Dispose();
            HOperatorSet.Emphasize(ho_Image, out ho_ImageEmphasize, 5, 5, 5);
            ho_ImageMedian.Dispose();
            HOperatorSet.MedianImage(ho_ImageEmphasize, out ho_ImageMedian, "circle", 3,
                "mirrored");
            ho_ImageOpening.Dispose();
            HOperatorSet.GrayOpeningRect(ho_ImageMedian, out ho_ImageOpening, 2, 2);
            ho_GrayImage1.Dispose();
            HOperatorSet.Rgb1ToGray(ho_ImageOpening, out ho_GrayImage1);
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_GrayImage1, ho_ROI_0, out ho_ImageReduced);
            hv_ModelID.Dispose();
            HOperatorSet.CreateScaledShapeModel(ho_ImageReduced, "auto", 0, 6.28, "auto",
                0.9, 1.1, "auto", "auto", "use_polarity", "auto", "auto", out hv_ModelID);
            ho_Region.Dispose(); hv_UsedThreshold.Dispose();
            HOperatorSet.BinaryThreshold(ho_ImageReduced, out ho_Region, "max_separability",
                "dark", out hv_UsedThreshold);
            ho_RegionUnion.Dispose();
            HOperatorSet.Union1(ho_Region, out ho_RegionUnion);
            HOperatorSet.WriteRegion(ho_RegionUnion, hv_RegionPath);
            HOperatorSet.WriteShapeModel(hv_ModelID, hv_ModelID_Paht);
            HOperatorSet.WriteRegion(ho_ROI_0, hv_ROI_Path);
            ho_ImageEmphasize.Dispose();
            ho_ImageMedian.Dispose();
            ho_ImageOpening.Dispose();
            ho_GrayImage1.Dispose();
            ho_ImageReduced.Dispose();
            ho_Region.Dispose();

            hv_ModelID.Dispose();
            hv_UsedThreshold.Dispose();

            return;
        }
        // Local procedures 
        public void GetScreen(HObject ho_ImageRotate, out HObject ho_ImagePart, out HObject ho_ImageEmphasize, out HTuple hv_Phi)
        {



            // Local iconic variables 

            HObject ho_ImageGray, ho_Region = null, ho_ConnectedRegions = null;
            HObject ho_SelectedRegions = null, ho_Rectangle, ho_ImageReduced;
            HObject ho_ImageScaled, ho_ImageMedian;

            // Local control variables 

            HTuple hv_thresholdMax = new HTuple(), hv_Index = new HTuple();
            HTuple hv_Number = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Length1 = new HTuple();
            HTuple hv_Length2 = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize);
            HOperatorSet.GenEmptyObj(out ho_ImageGray);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_ImageScaled);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            hv_Phi = new HTuple();
            ho_ImageGray.Dispose();
            HOperatorSet.Rgb3ToGray(ho_ImageRotate, ho_ImageRotate, ho_ImageRotate, out ho_ImageGray
                );
            hv_thresholdMax.Dispose();
            hv_thresholdMax = 180;
            for (hv_Index = 1; (int)hv_Index <= 10; hv_Index = (int)hv_Index + 1)
            {
                ho_Region.Dispose();
                HOperatorSet.Threshold(ho_ImageGray, out ho_Region, 0, hv_thresholdMax);
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_Region, out ho_ConnectedRegions);
                ho_SelectedRegions.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area",
                    "and", 150000, 400000);
                hv_Number.Dispose();
                HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number);
                if ((int)(new HTuple(hv_Number.TupleGreater(0))) != 0)
                {
                    break;
                }
                else
                {
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        {
                            HTuple
                              ExpTmpLocalVar_thresholdMax = hv_thresholdMax + 20;
                            hv_thresholdMax.Dispose();
                            hv_thresholdMax = ExpTmpLocalVar_thresholdMax;
                        }
                    }
                }
            }
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Phi.Dispose(); hv_Length1.Dispose(); hv_Length2.Dispose();
            HOperatorSet.SmallestRectangle2(ho_SelectedRegions, out hv_Row, out hv_Column,
                out hv_Phi, out hv_Length1, out hv_Length2);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row, hv_Column, hv_Phi, hv_Length1 + 20,
                    hv_Length2 + 20);
            }
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageGray, ho_Rectangle, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            ho_ImageScaled.Dispose();
            HOperatorSet.ScaleImage(ho_ImagePart, out ho_ImageScaled, Scaled_Value1, Scaled_Value2);
            ho_ImageMedian.Dispose();
            HOperatorSet.MedianImage(ho_ImageScaled, out ho_ImageMedian, "circle", 3, "mirrored");
            ho_ImageEmphasize.Dispose();
            HOperatorSet.Emphasize(ho_ImageMedian, out ho_ImageEmphasize, 7, 7, 1);
            ho_ImageGray.Dispose();
            ho_Region.Dispose();
            ho_ConnectedRegions.Dispose();
            ho_SelectedRegions.Dispose();
            ho_Rectangle.Dispose();
            ho_ImageReduced.Dispose();
            ho_ImageScaled.Dispose();
            ho_ImageMedian.Dispose();

            hv_thresholdMax.Dispose();
            hv_Index.Dispose();
            hv_Number.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Length1.Dispose();
            hv_Length2.Dispose();

            return;
        }
        public void Get_Screen_Black(HObject ho_ImageRotate, out HObject ho_ImagePart, out HObject ho_ImageEmphasize, HTuple hv_ModelID, out HTuple hv_Angle)
        {

            // Local iconic variables 

            HObject ho_ImageGray, ho_Rectangle, ho_ImageReduced;
            HObject ho_ImageScaled, ho_ImageMedian;

            // Local control variables 

            HTuple hv_Row = new HTuple(), hv_Column = new HTuple();
            HTuple hv_Scale = new HTuple(), hv_Score = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize);
            HOperatorSet.GenEmptyObj(out ho_ImageGray);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_ImageScaled);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            hv_Angle = new HTuple();
            ho_ImageGray.Dispose();
            HOperatorSet.Rgb3ToGray(ho_ImageRotate, ho_ImageRotate, ho_ImageRotate, out ho_ImageGray
                );
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
            HOperatorSet.FindScaledShapeModel(ho_ImageGray, hv_ModelID, -0.39, 0.78, 0.9,
                1.1, 0.5, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                out hv_Scale, out hv_Score);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row + 590, hv_Column - 35, hv_Angle,
                    340, 500);
            }
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageGray, ho_Rectangle, out ho_ImageReduced);
            ho_ImagePart.Dispose();
            HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            ho_ImageScaled.Dispose();
            HOperatorSet.ScaleImage(ho_ImagePart, out ho_ImageScaled, Scaled_Value1, Scaled_Value2);
            ho_ImageMedian.Dispose();
            HOperatorSet.MedianImage(ho_ImageScaled, out ho_ImageMedian, "circle", 3, "mirrored");
            ho_ImageEmphasize.Dispose();
            HOperatorSet.Emphasize(ho_ImageMedian, out ho_ImageEmphasize, 15, 15, 2);
            ho_ImageGray.Dispose();
            ho_Rectangle.Dispose();
            ho_ImageReduced.Dispose();
            ho_ImageScaled.Dispose();
            ho_ImageMedian.Dispose();

            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();

            return;
        }
        public void Test_Screen(HObject ho_Image, HObject ho_ROI_0, HObject ho_RegionUnion, out HObject ho_SelectedRegions, HTuple hv_threshold_Value, HTuple hv_ModelID, out HTuple hv_Result)
        {
            // Local iconic variables 

            HObject ho_ImageEmphasize, ho_ImageMedian;
            HObject ho_ImageOpening, ho_GrayImage, ho_RegionAffineTrans1 = null;
            HObject ho_ImageReduced = null, ho_Region = null, ho_RegionAffineTrans = null;
            HObject ho_RegionDifference = null, ho_RegionOpening = null;
            HObject ho_out_region1 = null;

            // Local control variables 

            HTuple hv_Area = new HTuple(), hv_Row1 = new HTuple();
            HTuple hv_Column1 = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Angle = new HTuple();
            HTuple hv_Scale = new HTuple(), hv_Score = new HTuple();
            HTuple hv_HomMat2DIdentity = new HTuple(), hv_HomMat2DRotate = new HTuple();
            HTuple hv_HomMat2DTranslate = new HTuple(), hv_HomMat2DScale = new HTuple();
            HTuple hv_UsedThreshold = new HTuple(), hv_erro_ng = new HTuple();
            HTuple hv_Number = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            HOperatorSet.GenEmptyObj(out ho_ImageOpening);
            HOperatorSet.GenEmptyObj(out ho_GrayImage);
            HOperatorSet.GenEmptyObj(out ho_RegionAffineTrans1);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_RegionAffineTrans);
            HOperatorSet.GenEmptyObj(out ho_RegionDifference);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening);
            HOperatorSet.GenEmptyObj(out ho_out_region1);
            hv_Result = new HTuple();
            ho_ImageEmphasize.Dispose();
            HOperatorSet.Emphasize(ho_Image, out ho_ImageEmphasize, 5, 5, 3);
            ho_ImageMedian.Dispose();
            HOperatorSet.MedianImage(ho_ImageEmphasize, out ho_ImageMedian, "circle", 3,
                "mirrored");
            ho_ImageOpening.Dispose();
            HOperatorSet.GrayOpeningRect(ho_ImageMedian, out ho_ImageOpening, 2, 2);
            ho_GrayImage.Dispose();
            HOperatorSet.Rgb1ToGray(ho_ImageOpening, out ho_GrayImage);

            hv_Area.Dispose(); hv_Row1.Dispose(); hv_Column1.Dispose();
            HOperatorSet.AreaCenter(ho_ROI_0, out hv_Area, out hv_Row1, out hv_Column1);
            using (HDevDisposeHelper dh = new HDevDisposeHelper())
            {
                hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
                HOperatorSet.FindScaledShapeModel(ho_GrayImage, hv_ModelID, (new HTuple(-30)).TupleRad()
                    , (new HTuple(30)).TupleRad(), 0.9, 1.1, 0.2, 1, 0.5, (new HTuple("least_squares")).TupleConcat(
                    "max_deformation 3"), 0, 0.9, out hv_Row, out hv_Column, out hv_Angle, out hv_Scale,
                    out hv_Score);
            }
            if ((int)(new HTuple(hv_Row.TupleGreater(0))) != 0)
            {
                hv_HomMat2DIdentity.Dispose();
                HOperatorSet.HomMat2dIdentity(out hv_HomMat2DIdentity);
                hv_HomMat2DRotate.Dispose();
                HOperatorSet.HomMat2dRotate(hv_HomMat2DIdentity, hv_Angle, hv_Row, hv_Column,
                    out hv_HomMat2DRotate);
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    hv_HomMat2DTranslate.Dispose();
                    HOperatorSet.HomMat2dTranslate(hv_HomMat2DRotate, hv_Row - hv_Row1, hv_Column - hv_Column1,
                        out hv_HomMat2DTranslate);
                }
                hv_HomMat2DScale.Dispose();
                HOperatorSet.HomMat2dScale(hv_HomMat2DTranslate, hv_Scale, hv_Scale, hv_Row,
                    hv_Column, out hv_HomMat2DScale);
                ho_RegionAffineTrans1.Dispose();
                HOperatorSet.AffineTransRegion(ho_ROI_0, out ho_RegionAffineTrans1, hv_HomMat2DScale,
                    "nearest_neighbor");
                ho_ImageReduced.Dispose();
                HOperatorSet.ReduceDomain(ho_GrayImage, ho_RegionAffineTrans1, out ho_ImageReduced
                    );
                ho_Region.Dispose(); hv_UsedThreshold.Dispose();
                HOperatorSet.BinaryThreshold(ho_ImageReduced, out ho_Region, "max_separability",
                    "dark", out hv_UsedThreshold);
                ho_RegionAffineTrans.Dispose();
                HOperatorSet.AffineTransRegion(ho_RegionUnion, out ho_RegionAffineTrans, hv_HomMat2DScale,
                    "nearest_neighbor");
                ho_RegionDifference.Dispose();
                HOperatorSet.Difference(ho_RegionAffineTrans, ho_Region, out ho_RegionDifference
                    );
                ho_RegionOpening.Dispose();
                HOperatorSet.OpeningRectangle1(ho_RegionDifference, out ho_RegionOpening, 3,
                    3);
                ho_out_region1.Dispose();
                HOperatorSet.Connection(ho_RegionOpening, out ho_out_region1);
                hv_erro_ng.Dispose();
                hv_erro_ng = 1;
            }
            else
            {
                hv_erro_ng.Dispose();
                hv_erro_ng = 0;
            }
            //*根据图文区域的大小，调整检测参数的范围
            if ((int)(new HTuple(hv_erro_ng.TupleEqual(1))) != 0)
            {
                ho_SelectedRegions.Dispose();
                if (Screen_AreaMin == 0) Screen_AreaMin = 175;
                HOperatorSet.SelectShape(ho_out_region1, out ho_SelectedRegions, "area", "and",
                    Screen_AreaMin, 99999);
                hv_Number.Dispose();
                HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number);
                if ((int)((new HTuple(hv_Number.TupleLess(1))).TupleAnd(new HTuple(hv_erro_ng.TupleEqual(
                    1)))) != 0)
                {
                    hv_Result.Dispose();
                    hv_Result = 1;
                }
                else
                {
                    hv_Result.Dispose();
                    hv_Result = 2;
                }
            }
            else
            {
                hv_Result.Dispose();
                hv_Result = 2;
            }
            ho_ImageEmphasize.Dispose();
            ho_ImageMedian.Dispose();
            ho_ImageOpening.Dispose();
            ho_GrayImage.Dispose();
            ho_RegionAffineTrans1.Dispose();
            ho_ImageReduced.Dispose();
            ho_Region.Dispose();
            ho_RegionAffineTrans.Dispose();
            ho_RegionDifference.Dispose();
            ho_RegionOpening.Dispose();
            ho_out_region1.Dispose();

            hv_Area.Dispose();
            hv_Row1.Dispose();
            hv_Column1.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Angle.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();
            hv_HomMat2DIdentity.Dispose();
            hv_HomMat2DRotate.Dispose();
            hv_HomMat2DTranslate.Dispose();
            hv_HomMat2DScale.Dispose();
            hv_UsedThreshold.Dispose();
            hv_erro_ng.Dispose();
            hv_Number.Dispose();

            return;
        }
        public void Test_Key(HObject ho_Image, HObject ho_ROI_0, HObject ho_RegionUnion, out HObject ho_out_region1, HTuple hv_ModelID, out HTuple hv_erro_ng)
        {




            // Local iconic variables 

            HObject ho_ImageEmphasize, ho_ImageMedian;
            HObject ho_ImageOpening, ho_GrayImage, ho_ModelContours;
            HObject ho_RegionAffineTrans = null, ho_Rectangle = null, ho_ImageReduced = null;
            HObject ho_Region1 = null, ho_RegionDifference = null, ho_RegionOpening = null;

            // Local control variables 

            HTuple hv_Area = new HTuple(), hv_Row1 = new HTuple();
            HTuple hv_Column1 = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Angle = new HTuple();
            HTuple hv_Scale = new HTuple(), hv_Score = new HTuple();
            HTuple hv_HomMat2DIdentity = new HTuple(), hv_HomMat2DRotate = new HTuple();
            HTuple hv_HomMat2DTranslate = new HTuple(), hv_HomMat2DScale = new HTuple();
            HTuple hv_Row11 = new HTuple(), hv_Column11 = new HTuple();
            HTuple hv_Row2 = new HTuple(), hv_Column2 = new HTuple();
            HTuple hv_UsedThreshold1 = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_out_region1);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            HOperatorSet.GenEmptyObj(out ho_ImageOpening);
            HOperatorSet.GenEmptyObj(out ho_GrayImage);
            HOperatorSet.GenEmptyObj(out ho_ModelContours);
            HOperatorSet.GenEmptyObj(out ho_RegionAffineTrans);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Region1);
            HOperatorSet.GenEmptyObj(out ho_RegionDifference);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening);
            hv_erro_ng = new HTuple();
            try
            {
                ho_ImageEmphasize.Dispose();
                HOperatorSet.Emphasize(ho_Image, out ho_ImageEmphasize, 5, 5, 3);
                ho_ImageMedian.Dispose();
                HOperatorSet.MedianImage(ho_ImageEmphasize, out ho_ImageMedian, "circle", 3,
                    "mirrored");
                ho_ImageOpening.Dispose();
                HOperatorSet.GrayOpeningRect(ho_ImageMedian, out ho_ImageOpening, 2, 2);
                ho_GrayImage.Dispose();
                HOperatorSet.Rgb1ToGray(ho_ImageOpening, out ho_GrayImage);
                ho_ModelContours.Dispose();
                HOperatorSet.GetShapeModelContours(out ho_ModelContours, hv_ModelID, 1);
                hv_Area.Dispose(); hv_Row1.Dispose(); hv_Column1.Dispose();
                HOperatorSet.AreaCenter(ho_ROI_0, out hv_Area, out hv_Row1, out hv_Column1);
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
                    HOperatorSet.FindScaledShapeModel(ho_GrayImage, hv_ModelID, (new HTuple(-30)).TupleRad()
                        , (new HTuple(30)).TupleRad(), 0.8, 1.2, 0.4, 1, 0.5, (new HTuple("least_squares")).TupleConcat(
                        "max_deformation 3"), 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                        out hv_Scale, out hv_Score);
                }
                if ((int)(new HTuple(hv_Row.TupleGreater(0))) != 0)
                {
                    hv_HomMat2DIdentity.Dispose();
                    HOperatorSet.HomMat2dIdentity(out hv_HomMat2DIdentity);
                    hv_HomMat2DRotate.Dispose();
                    HOperatorSet.HomMat2dRotate(hv_HomMat2DIdentity, hv_Angle, hv_Row, hv_Column,
                        out hv_HomMat2DRotate);
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        hv_HomMat2DTranslate.Dispose();
                        HOperatorSet.HomMat2dTranslate(hv_HomMat2DRotate, hv_Row - hv_Row1, hv_Column - hv_Column1,
                            out hv_HomMat2DTranslate);
                    }
                    hv_HomMat2DScale.Dispose();
                    HOperatorSet.HomMat2dScale(hv_HomMat2DTranslate, hv_Scale, hv_Scale, hv_Row,
                        hv_Column, out hv_HomMat2DScale);
                    ho_RegionAffineTrans.Dispose();
                    HOperatorSet.AffineTransRegion(ho_RegionUnion, out ho_RegionAffineTrans,
                        hv_HomMat2DScale, "nearest_neighbor");
                    hv_Row11.Dispose(); hv_Column11.Dispose(); hv_Row2.Dispose(); hv_Column2.Dispose();
                    HOperatorSet.SmallestRectangle1(ho_RegionAffineTrans, out hv_Row11, out hv_Column11,
                        out hv_Row2, out hv_Column2);
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        ho_Rectangle.Dispose();
                        HOperatorSet.GenRectangle1(out ho_Rectangle, hv_Row11 - 5, hv_Column11 - 5, hv_Row2 + 5,
                            hv_Column2 + 5);
                    }

                    ho_ImageReduced.Dispose();
                    HOperatorSet.ReduceDomain(ho_GrayImage, ho_Rectangle, out ho_ImageReduced
                        );
                    ho_Region1.Dispose(); hv_UsedThreshold1.Dispose();
                    HOperatorSet.BinaryThreshold(ho_ImageReduced, out ho_Region1, "max_separability",
                        "dark", out hv_UsedThreshold1);

                    ho_RegionDifference.Dispose();
                    HOperatorSet.Difference(ho_RegionAffineTrans, ho_Region1, out ho_RegionDifference
                        );
                    ho_RegionOpening.Dispose();
                    HOperatorSet.OpeningRectangle1(ho_RegionDifference, out ho_RegionOpening,
                        3, 3);
                    ho_out_region1.Dispose();
                    HOperatorSet.Connection(ho_RegionOpening, out ho_out_region1);
                    hv_erro_ng.Dispose();
                    hv_erro_ng = 1;
                }
                else
                {
                    hv_erro_ng.Dispose();
                    hv_erro_ng = 0;
                }
                ho_ImageEmphasize.Dispose();
                ho_ImageMedian.Dispose();
                ho_ImageOpening.Dispose();
                ho_GrayImage.Dispose();
                ho_ModelContours.Dispose();
                ho_RegionAffineTrans.Dispose();
                ho_Rectangle.Dispose();
                ho_ImageReduced.Dispose();
                ho_Region1.Dispose();
                ho_RegionDifference.Dispose();
                ho_RegionOpening.Dispose();

                hv_Area.Dispose();
                hv_Row1.Dispose();
                hv_Column1.Dispose();
                hv_Row.Dispose();
                hv_Column.Dispose();
                hv_Angle.Dispose();
                hv_Scale.Dispose();
                hv_Score.Dispose();
                hv_HomMat2DIdentity.Dispose();
                hv_HomMat2DRotate.Dispose();
                hv_HomMat2DTranslate.Dispose();
                hv_HomMat2DScale.Dispose();
                hv_Row11.Dispose();
                hv_Column11.Dispose();
                hv_Row2.Dispose();
                hv_Column2.Dispose();
                hv_UsedThreshold1.Dispose();

                return;
            }
            catch (HalconException HDevExpDefaultException)
            {
                ho_ImageEmphasize.Dispose();
                ho_ImageMedian.Dispose();
                ho_ImageOpening.Dispose();
                ho_GrayImage.Dispose();
                ho_ModelContours.Dispose();
                ho_RegionAffineTrans.Dispose();
                ho_Rectangle.Dispose();
                ho_ImageReduced.Dispose();
                ho_Region1.Dispose();
                ho_RegionDifference.Dispose();
                ho_RegionOpening.Dispose();

                hv_Area.Dispose();
                hv_Row1.Dispose();
                hv_Column1.Dispose();
                hv_Row.Dispose();
                hv_Column.Dispose();
                hv_Angle.Dispose();
                hv_Scale.Dispose();
                hv_Score.Dispose();
                hv_HomMat2DIdentity.Dispose();
                hv_HomMat2DRotate.Dispose();
                hv_HomMat2DTranslate.Dispose();
                hv_HomMat2DScale.Dispose();
                hv_Row11.Dispose();
                hv_Column11.Dispose();
                hv_Row2.Dispose();
                hv_Column2.Dispose();
                hv_UsedThreshold1.Dispose();

                throw HDevExpDefaultException;
            }
        }
        public void ScreenModel_Create(HObject ho_Image, HObject ho_ROI_0, out HObject ho_RegionUnion, HTuple hv_GrayValue, HTuple hv_RegionPath, HTuple hv_ModelID_Paht, HTuple hv_ROI_Path)
        {
            // Local iconic variables 

            HObject ho_ImageEmphasize, ho_ImageMedian;
            HObject ho_ImageOpening, ho_GrayImage1, ho_ImageReduced;
            HObject ho_Region, ho_ConnectedRegions;

            // Local control variables 

            HTuple hv_ModelID = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_RegionUnion);
            HOperatorSet.GenEmptyObj(out ho_ImageEmphasize);
            HOperatorSet.GenEmptyObj(out ho_ImageMedian);
            HOperatorSet.GenEmptyObj(out ho_ImageOpening);
            HOperatorSet.GenEmptyObj(out ho_GrayImage1);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            ho_ImageEmphasize.Dispose();
            HOperatorSet.Emphasize(ho_Image, out ho_ImageEmphasize, 5, 5, 5);
            ho_ImageMedian.Dispose();
            HOperatorSet.MedianImage(ho_ImageEmphasize, out ho_ImageMedian, "circle", 3,
                "mirrored");
            ho_ImageOpening.Dispose();
            HOperatorSet.GrayOpeningRect(ho_ImageMedian, out ho_ImageOpening, 2, 2);
            ho_GrayImage1.Dispose();
            HOperatorSet.Rgb1ToGray(ho_ImageOpening, out ho_GrayImage1);
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_GrayImage1, ho_ROI_0, out ho_ImageReduced);
            hv_ModelID.Dispose();
            HOperatorSet.CreateScaledShapeModel(ho_ImageReduced, "auto", 0, 6.28, "auto",
                0.9, 1.1, "auto", "auto", "use_polarity", "auto", "auto", out hv_ModelID);
            ho_Region.Dispose();
            HOperatorSet.Threshold(ho_ImageReduced, out ho_Region, 0, hv_GrayValue);
            ho_ConnectedRegions.Dispose();
            HOperatorSet.Connection(ho_Region, out ho_ConnectedRegions);
            ho_RegionUnion.Dispose();
            HOperatorSet.Union1(ho_ConnectedRegions, out ho_RegionUnion);
            HOperatorSet.WriteRegion(ho_RegionUnion, hv_RegionPath);
            HOperatorSet.WriteShapeModel(hv_ModelID, hv_ModelID_Paht);
            HOperatorSet.WriteRegion(ho_ROI_0, hv_ROI_Path);
            ho_ImageEmphasize.Dispose();
            ho_ImageMedian.Dispose();
            ho_ImageOpening.Dispose();
            ho_GrayImage1.Dispose();
            ho_ImageReduced.Dispose();
            ho_Region.Dispose();
            ho_ConnectedRegions.Dispose();

            hv_ModelID.Dispose();

            return;
        }
        public void Get_Local_image(HObject ho_ImagePart, out HObject ho_Image1)
        {



            // Local iconic variables 

            HObject ho_Domain;

            // Local control variables 

            HTuple hv_Width = new HTuple(), hv_Height = new HTuple();
            HTuple hv_Rows = new HTuple(), hv_Columns = new HTuple();
            HTuple hv_Grayval = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_Image1);
            HOperatorSet.GenEmptyObj(out ho_Domain);
            hv_Width.Dispose(); hv_Height.Dispose();
            HOperatorSet.GetImageSize(ho_ImagePart, out hv_Width, out hv_Height);
            ho_Domain.Dispose();
            HOperatorSet.GetDomain(ho_ImagePart, out ho_Domain);
            hv_Rows.Dispose(); hv_Columns.Dispose();
            HOperatorSet.GetRegionPoints(ho_Domain, out hv_Rows, out hv_Columns);
            hv_Grayval.Dispose();
            HOperatorSet.GetGrayval(ho_ImagePart, hv_Rows, hv_Columns, out hv_Grayval);
            ho_Image1.Dispose();
            HOperatorSet.GenImageConst(out ho_Image1, "byte", hv_Width, hv_Height);
            HOperatorSet.SetGrayval(ho_Image1, hv_Rows, hv_Columns, hv_Grayval);
            ho_Domain.Dispose();

            hv_Width.Dispose();
            hv_Height.Dispose();
            hv_Rows.Dispose();
            hv_Columns.Dispose();
            hv_Grayval.Dispose();

            return;
        }
        public void Get_KeyPart(HObject ho_ImageRotate, out HObject ho_ImagePart, HTuple hv_ModelID, HTuple hv_YKQ_Width, HTuple hv_YKQ_Height, out HTuple hv_Length)
        {




            // Local iconic variables 

            HObject ho_Rectangle = null, ho_ImageReduced = null;

            // Local control variables 

            HTuple hv_Row = new HTuple(), hv_Column = new HTuple();
            HTuple hv_Angle = new HTuple(), hv_Scale = new HTuple();
            HTuple hv_Score = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImagePart);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            hv_Length = new HTuple();
            hv_Row.Dispose(); hv_Column.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();
            HOperatorSet.FindScaledShapeModel(ho_ImageRotate, hv_ModelID, -0.39, 0.78, 0.9,
                1.1, 0.5, 1, 0.5, "least_squares", 0, 0.9, out hv_Row, out hv_Column, out hv_Angle,
                out hv_Scale, out hv_Score);
            hv_Length.Dispose();
            HOperatorSet.TupleLength(hv_Score, out hv_Length);
            if ((int)(new HTuple(hv_Length.TupleGreater(0))) != 0)
            {
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row, hv_Column, hv_Angle, hv_YKQ_Width,
                    hv_YKQ_Height);
                ho_ImageReduced.Dispose();
                HOperatorSet.ReduceDomain(ho_ImageRotate, ho_Rectangle, out ho_ImageReduced
                    );
                ho_ImagePart.Dispose();
                HOperatorSet.CropDomain(ho_ImageReduced, out ho_ImagePart);
            }
            ho_Rectangle.Dispose();
            ho_ImageReduced.Dispose();

            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Angle.Dispose();
            hv_Scale.Dispose();
            hv_Score.Dispose();

            return;
        }
        public void Key_Create_Part_Model(HObject ho_GrayImage, HObject ho_ROI_0, HTuple hv_SaveModePath, out HTuple hv_ModelID1)
        {




            // Local iconic variables 

            HObject ho_ImageReduced;
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            hv_ModelID1 = new HTuple();
            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_GrayImage, ho_ROI_0, out ho_ImageReduced);
            hv_ModelID1.Dispose();
            HOperatorSet.CreateScaledShapeModel(ho_ImageReduced, "auto", -0.39, 0.79, "auto",
                0.9, 1.1, "auto", "auto", "use_polarity", "auto", "auto", out hv_ModelID1);
            HOperatorSet.WriteShapeModel(hv_ModelID1, hv_SaveModePath);
            ho_ImageReduced.Dispose();


            return;
        }
    }

    public class Tool
    {
        public static string BinConvertHex(string binString)
        {
            try
            {
                string hexadecimalNumber = "";
                string binaryString = binString.Replace("L", "").Replace("S", "");

                byte[] byteArray = Enumerable.Range(0, binaryString.Length / 8).Select(i => Convert.ToByte(binaryString.Substring(i * 8, 8), 2)).ToArray();
                hexadecimalNumber = BitConverter.ToString(byteArray).Replace("-", "");
                return hexadecimalNumber;
            }
            catch
            {
                return "error";
            }
        }

        public static bool compareCode(string Code1, string Code2, double Score)
        {
            bool Result = false;
            if ((Code1 == "" && Code2 != "") || (Code1 != "" && Code2 == ""))
            {
                Result = false;
            }

            if (Code1 != null && Code2 != null && Code1.Length>5 && (Code1.Substring(0,6)==Code2.Substring(0,6)))
            {
                
                Result = true;
            }
            else
            {
                Result = false;
            }
            return Result;
        }
        public static bool compareCode(List<string> code1,List<string> code2)
        {
            bool Result = false;
            if (code1.Count > 0 && code2.Count > 0)
            {
                for (int i = 0; i < code1.Count; i++)
                {
                    for (int k = 0; k < code2.Count; k++)
                    {
                        if (code1[i] == code2[k])
                        {
                            Result = true;
                            break;
                        }
                    }
                    if (Result == true) break;
                }
            }
            return Result;

        }


    }


    public class IRTestInfo
    {
        public string IRString = "";
        public MotionPoint Point = new MotionPoint();
    }

    public class YKQFeature
    {
        public List<ExamineFeatrue> ScreenFeatures = new List<ExamineFeatrue>();
        public List<ExamineFeatrue> KeyFeatures = new List<ExamineFeatrue>();
    }

    public class ExamineFeatrue
    {
        public HObject FeatureROI = new HObject();
        public HObject FeatureRegion = new HObject();
        public HTuple Model = new HTuple();
    }

    public class YKQ_Test
    {

        public Config configFile {  get; set; }
        public YKQFeature ykqFeature = new YKQFeature();
        public int NowProductID {  get; set; }
        private Algorithm algorithm = new Algorithm();
        public TestStation TestStation = new TestStation("");
        public List<Bitmap> Image_Screen = new List<Bitmap>();
        public List<Bitmap> Image_Key = new List<Bitmap>();
        public bool SavaImage = false;
        public ListBox listBox = new ListBox();
        public  List<HSmartWindowControl> HwindowsList = new List<HSmartWindowControl>();
        public string LastDevNo = "";
        public int ReTest = 2;
        List< bool> ReTestState = new List<bool>();
        public int Key_AreaMin { get; set; }
        private void Vision(TestStation testStation, string TestPostion, List<Bitmap> ImageList, HSmartWindowControl windows1, HSmartWindowControl windows2, HSmartWindowControl windows3, HSmartWindowControl windows4, ListBox listBox)
        {
            LastDevNo = GetLastDriveNo();
            Random random = new Random();
            if (TestPostion == "Screen")
            {

                //保存一下图片
                if (Directory.Exists( LastDevNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model) == false)
                {
                    Directory.CreateDirectory(LastDevNo +  @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model);
                }
                if (SavaImage == true)
                {
                    ImageList[0].Save(LastDevNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "A.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageList[1].Save(LastDevNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "B.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageList[2].Save(LastDevNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "C.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageList[3].Save(LastDevNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "D.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                testStation.Channel1.Test_item_LCD = ScreenTest(windows1, ImageList[0], random.Next(), listBox, out testStation.Channel1.ScreenIsEmpty);
                testStation.Channel2.Test_item_LCD = ScreenTest(windows2, ImageList[1], random.Next(), listBox, out testStation.Channel2.ScreenIsEmpty);
                testStation.Channel3.Test_item_LCD = ScreenTest(windows3, ImageList[2], random.Next(), listBox, out testStation.Channel3.ScreenIsEmpty);
                testStation.Channel4.Test_item_LCD = ScreenTest(windows4, ImageList[3], random.Next(), listBox, out testStation.Channel4.ScreenIsEmpty);
            }

            if (TestPostion == "Key")
            {
                //保存一下图片
                if (Directory.Exists(LastDevNo + @":\SaveImage\KeyTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model) == false)
                {
                    Directory.CreateDirectory(LastDevNo + @":\SaveImage\KeyTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model);
                }

                if (SavaImage == true)
                {
                    ImageList[0].Save(LastDevNo + @":\SaveImage\KeyTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "A.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageList[1].Save(LastDevNo + @":\SaveImage\KeyTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "B.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageList[2].Save(LastDevNo + @":\SaveImage\KeyTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "C.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageList[3].Save(LastDevNo + @":\SaveImage\KeyTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "D.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                testStation.Channel1.Test_item_Key = KeyTest(windows1, ImageList[0], out testStation.Channel1.KeyIsEmpty);
                testStation.Channel2.Test_item_Key = KeyTest(windows2, ImageList[1], out testStation.Channel2.KeyIsEmpty);
                testStation.Channel3.Test_item_Key = KeyTest(windows3, ImageList[2], out testStation.Channel3.KeyIsEmpty);
                testStation.Channel4.Test_item_Key = KeyTest(windows4, ImageList[3], out testStation.Channel4.KeyIsEmpty);
            }
        }

        public void Run()
        {
            algorithm.Scaled_Value1 = configFile.productList[NowProductID].GetScreen_Scaled_Value1;
            algorithm.Scaled_Value2 = configFile.productList[NowProductID].GetScreen_Scaled_Value2;
            algorithm.Screen_AreaMin = configFile.productList[NowProductID].Screen_AreaMin;


            for (int i = 0; i < ReTest; i++)
            {
                ReTestState.Clear();
                Vision(TestStation, "Key", Image_Key, HwindowsList[4], HwindowsList[5], HwindowsList[6], HwindowsList[7], listBox);
                if (ReTestState.Contains(false) == false) break;
            }


            for (int i = 0; i < ReTest; i++)
            {
                ReTestState.Clear();
                Vision(TestStation, "Screen", Image_Screen, HwindowsList[0], HwindowsList[1], HwindowsList[2], HwindowsList[3], listBox);
                if(ReTestState.Contains(false) == false ) break;
            }
        }

        private ScreenResult ScreenTest(HSmartWindowControl hSmartWindow, Bitmap image, int imgindex, ListBox listBox,out bool IsEmpty)
        {
            IsEmpty = false;
            ScreenResult testResult = new ScreenResult();
            HObject Image_H = new HObject();
            HTuple ang = new HTuple();
            HTuple hTuple = new HTuple();
            HTuple Hwindos = new HTuple(hSmartWindow.HalconWindow);
            HTuple Test_Result = new HTuple();
            HObject ROI = new HObject();
            HObject ScreenModelROI = new HObject();
            HObject Region_H = new HObject();
            HTuple ModelID = new HTuple();
            HObject Result_Region = new HObject();
            HTuple NG_Result = new HTuple();
            HTuple Count_obj = new HTuple();
            HObject SelectedRegions = new HObject();
            HObject ImageRotate = new HObject();
            HObject NG_Region = new HObject();
            HObject YJImage = new HObject();
            HObject YJImage_Em = new HObject();

            int NGcount = 0;
            string LastDriveNo = GetLastDriveNo();
            if (Directory.Exists(Directory.GetCurrentDirectory() + @"\ProductModel\Screen\" + configFile.productList[NowProductID].Screen_Model + @"\ModelID") == true)
            {


                if (image != null)
                {
                    ImageConvert.Bitmap2HObjectS(image, out Image_H);
                    HOperatorSet.RotateImage(Image_H, out ImageRotate, 90, "constant");
                    try
                    {
                        if (configFile.productList[NowProductID].P_Style == Product.Product_Style.RomoteControl_White)
                        {
                            algorithm.GetScreen(ImageRotate, out  YJImage, out YJImage_Em, out ang);
                        }

                        if (configFile.productList[NowProductID].P_Style == Product.Product_Style.RomoteControl_black)
                        {
                            HOperatorSet.ReadShapeModel(Directory.GetCurrentDirectory() + @"\Model\Black_FindModel", out HTuple ScreenFindModel);
                            algorithm.Get_Screen_Black(ImageRotate, out YJImage, out YJImage_Em, ScreenFindModel, out ang);
                        }

                        testResult.ScreenDisp = true;
                        //屏幕型号分类

                        HOperatorSet.GenEmptyRegion(out HObject out_NG_Region);
                        hSmartWindow.HalconWindow.ClearWindow();
                        HOperatorSet.GenEmptyObj(out NG_Region);
                        HOperatorSet.DispObj(YJImage_Em, hSmartWindow.HalconWindow);
                        hSmartWindow.SetFullImagePart();
                        HOperatorSet.SetColor(hSmartWindow.HalconWindow, "yellow");
                        if (ykqFeature.ScreenFeatures.Count > 0)
                        {
                            for (int i = 0; i < ykqFeature.ScreenFeatures.Count; i++)
                            {
                                algorithm.Test_Screen(YJImage_Em, ykqFeature.ScreenFeatures[i].FeatureROI, ykqFeature.ScreenFeatures[i].FeatureRegion, out Result_Region, 100, ykqFeature.ScreenFeatures[i].Model, out Test_Result);
                                if (Test_Result == 2)
                                {
                                    NGcount++;
                                    HOperatorSet.DispObj(Result_Region, hSmartWindow.HalconWindow);
                                    break;
                                }

                            }

                        }

                        Console.WriteLine("屏幕检测显示结果：" + NGcount);
                        algorithm.set_display_font(hSmartWindow.HalconWindow, 15, "mono", "true", "false");
                        if (NGcount > 0)
                        {
                            if (Directory.Exists(LastDriveNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\NGImage") == false)
                            {
                                Directory.CreateDirectory(LastDriveNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\NGImage");
                            }

                            HOperatorSet.WriteImage(YJImage_Em, "bmp", 0, LastDriveNo + @":\SaveImage\ScreenTest\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + configFile.productList[NowProductID].Model + @"\NGImage\" + DateTime.Now.ToString("HHmmss") + new Random().Next(1,100) + ".bmp");
                            testResult.ScreenClass = false;
                            algorithm.disp_message(hSmartWindow.HalconWindow, "NG", "window", 0, 0, "red", "true");
                            HOperatorSet.DispRegion(out_NG_Region, hSmartWindow.HalconWindow);
                        }
                        else
                        {

                            testResult.ScreenClass = true;
                            algorithm.disp_message(hSmartWindow.HalconWindow, "OK", "window", 0, 0, "green", "true");

                        }
                        ReTestState.Add(true);

                    }
                    catch (Exception error)
                    {
                        OpearationTxt.WriteIni("Log", DateTime.Now.ToString(), error.Message, Directory.GetCurrentDirectory() + @"\RunLog.ini");
                        testResult.ScreenClass = false;
                        algorithm.disp_message(hSmartWindow.HalconWindow, "系统自动复测", "window", 0, 0, "green", "true");
                        ReTestState.Add(false);
                        Application.DoEvents();
                        Thread.Sleep(1000);
                        IsEmpty = true;
                    }
                }
            }

            //释放掉所有资源
            Image_H.Dispose();
            ang.Dispose();
            hTuple.Dispose();
            ROI.Dispose();
            ScreenModelROI.Dispose();
            Region_H.Dispose();
            ModelID.Dispose();
            Result_Region.Dispose();
            YJImage.Dispose();
            YJImage_Em.Dispose();
            NG_Result.Dispose();
            Count_obj.Dispose();
            SelectedRegions.Dispose();
            ImageRotate.Dispose();
            NG_Region.Dispose();
            return testResult;

        }
        public bool KeyTest(HSmartWindowControl hSmartWindow, Bitmap image, out bool IsEmpty)
        {
            bool Result = false;
            int NGCount = 0;
            HObject Image_H = new HObject();
            HTuple ang = new HTuple(1.6).TupleRad() * -1;
            HTuple hTuple = new HTuple();
            HTuple w, h, number;
            HObject ROI = new HObject();
            HObject Region_H = new HObject();
            HTuple ModelID = new HTuple();
            HObject Result_Region = new HObject();
            HTuple NG_Result = new HTuple();
            HTuple Count_obj = new HTuple();
            HObject SelectedRegions = new HObject();
            HObject ImageRotate = new HObject();
            HObject NG_Region = new HObject();
            HObject testImage = new HObject();
            HObject KeyImage = new HObject();
            HTuple Key_Count = new HTuple();


            try
            {
                IsEmpty = false;
                ImageConvert.Bitmap2HObjectS(image, out Image_H);
                string ModelPath = Directory.GetCurrentDirectory() + @"\ProductModel\Key\" + configFile.productList[NowProductID].Key_Model + @"\KeyLocationModel";
                HOperatorSet.ReadShapeModel(ModelPath, out HTuple LocationModel);
                HOperatorSet.RotateImage(Image_H, out ImageRotate, 90, "constant");

                hSmartWindow.HalconWindow.ClearWindow();
                HOperatorSet.GenEmptyObj(out NG_Region);

                if (configFile.productList[NowProductID].P_Style == Product.Product_Style.RomoteControl_black)
                {

                    algorithm.Key_GetImagePart_Black(ImageRotate, out KeyImage, ModelPath);
                    HOperatorSet.InvertImage(KeyImage, out KeyImage);
                    testImage = KeyImage;
                    Key_Count= 1;
                }
                else
                {
                    //algorithm.Key_GetImagePart(ImageRotate, out KeyImage, ModelPath, out  Key_Count);
                    algorithm.Get_KeyPart(ImageRotate, out KeyImage, LocationModel, 500, 1400, out HTuple Length);
                    testImage = KeyImage;
                    Key_Count = Length;
                }
                HOperatorSet.DispObj(testImage, hSmartWindow.HalconWindow);
                hSmartWindow.SetFullImagePart();

                if (Key_Count.I > 0)
                {
                    HOperatorSet.DispObj(KeyImage, hSmartWindow.HalconWindow);
                    try
                    {
                        if (ykqFeature.KeyFeatures.Count > 0)
                        {
                            for (int i = 0; i < ykqFeature.KeyFeatures.Count; i++)
                            {

                                algorithm.Test_Key(testImage, ykqFeature.KeyFeatures[i].FeatureROI, ykqFeature.KeyFeatures[i].FeatureRegion, out Result_Region, ykqFeature.KeyFeatures[i].Model, out NG_Result);
                                HOperatorSet.CountObj(Result_Region, out number);
                                if (number.I > 0 && NG_Result.I == 1)
                                {
                                    HOperatorSet.SelectShape(Result_Region, out SelectedRegions, "area", "and", Key_AreaMin, 999999);
                                    HOperatorSet.DispRegion(SelectedRegions, hSmartWindow.HalconWindow);
                                    HOperatorSet.SetColor(hSmartWindow.HalconWindow, "#ff000080");
                                    algorithm.set_display_font(hSmartWindow.HalconWindow, 20, "mono", "true", "false");
                                    HOperatorSet.CountObj(SelectedRegions, out Count_obj);
                                    if (Count_obj > 0)
                                    {
                                        algorithm.disp_message(hSmartWindow.HalconWindow, "NG", "window", 0, 0, "red", "true");
                                        NGCount++;
                                        HOperatorSet.SetColor(hSmartWindow.HalconWindow, "red");
                                        HOperatorSet.DispRegion(SelectedRegions, hSmartWindow.HalconWindow);
                                        break;
                                    }
                                }
                                else
                                {
                                    NGCount++;
                                }
                            }
                        }
                        ReTestState.Add(true);
                    }
                    catch (Exception error)
                    {
                        OpearationTxt.WriteIni("Log", DateTime.Now.ToString(), error.Message, Directory.GetCurrentDirectory() + @"\RunLog.ini");
                        Result = false;
                        algorithm.disp_message(hSmartWindow.HalconWindow, "系统自动复测", "window", 0, 0, "green", "true");
                        ReTestState.Add(false);
                        Application.DoEvents();
                        Thread.Sleep(1000);
                    }


                    if (NGCount == 0)
                    {
                        algorithm.disp_message(hSmartWindow.HalconWindow, "OK", "window", 0, 0, "green", "true");
                        Result = true;
                    }
                    else
                    {
                        HOperatorSet.DispObj(NG_Region, hSmartWindow.HalconWindow);
                        algorithm.disp_message(hSmartWindow.HalconWindow, "NG", "window", 0, 0, "red", "true");
                        Result = false;
                    }
                }
                else
                {
                    IsEmpty = true;
                    HOperatorSet.GetImageSize(ImageRotate, out w, out h);
                    HOperatorSet.SetPart(hSmartWindow.HalconWindow, 0, 0, h - 1, w - 1);
                    HOperatorSet.DispObj(ImageRotate, hSmartWindow.HalconWindow);
                    algorithm.set_display_font(hSmartWindow.HalconWindow, 40, "mono", "true", "false");
                    algorithm.disp_message(hSmartWindow.HalconWindow, "Empty", "window", 0, 0, "red", "true");
                }

            }
            catch
            {

                IsEmpty = true;
            }




            Image_H.Dispose();
            ang.Dispose();
            hTuple.Dispose();
            ROI.Dispose();
            Region_H.Dispose();
            ModelID.Dispose();
            Result_Region.Dispose();
            NG_Result.Dispose();
            Count_obj.Dispose();
            SelectedRegions.Dispose();
            ImageRotate.Dispose();
            NG_Region.Dispose();
            testImage.Dispose();
            KeyImage.Dispose();
            Image_H.Dispose();
            Key_Count.Dispose();
            return Result;
        }
        private string GetLastDriveNo()
        {
            DriveInfo[] driveInfos = DriveInfo.GetDrives();
            List<DriveInfo> drives_List = new List<DriveInfo>();
            for (int i = 0; i < driveInfos.Length; i++)
            {
                if (driveInfos[i].DriveType == DriveType.Fixed) drives_List.Add(driveInfos[i]);
            }
            return drives_List[drives_List.Count - 1].Name.Substring(0, 1);
        }

    }

    public class Day_Total_Item
    {
        public string Total_Day = "";
        public Dictionary<string, int> Total_Itiem = new Dictionary<string, int>();
    }
    }
